2017-04-24 126 views
1

我有以下代码可执行以下操作: - 它需要温度和通道索引,并搜索对象列表(包含温度数组),并返回对象的索引,其中温度被发现。 我想这个方法结束时,找到的第一个,因为这是在其达到该温度的最早时间(它登陆)JavaFX:缺少返回语句

public int findRow(double targetTemperature, int ch) 
{ 
    //This method takes a double and finds it in the List, it then returns the element in which it is (the row) 
    //The element returned can be used with duration.between to find the response time between 2 known values 
    for (int i=0; i < readings.size(); i++) 
    { 
      double compareTemp = readings.get(i).getValue(ch); 
      if (compareTemp > targetTemperature) 
      { 
       System.out.println(readings.get(i).getTimestamp() + "is above target temp for channel " + ch); 
       return i; 
      } 
      else 
      { 
       System.out.println(readings.get(i).getTimestamp() + "Is not above target temp for channel " + ch); 
       return 0; 
      } 
    } 
} 

列表中包含TemperatureReadings这是我创建了一个类有两个变量:
- 值双打数组
- 带currentime的时间戳(当创建数组时)
我试图找到每个通道的响应时间。但是,当我运行上面的代码时,它表示“没有返回语句”,即使这两个选项都有返回语句(if/else)
或者如果您可以帮助我找出一个更好的方法来找到第一个存在列出该频道(阵列指数)的温度达到X度的地方,我真的很感激它。

其实我不希望如果可能的话,返回0返回错误或某事说“不温发现”或类似的东西

回答

1

Tuyen是正确的。另外,你不需要else语句。你会在第一个项目后返回。你只需要第一个if,然后在循环之外返回0;

尝试:

public int findRow(double targetTemperature, int ch) 
{ 
    //This method takes a double and finds it in the List, it then returns the element in which it is (the row) 
    //The element returned can be used with duration.between to find the response time between 2 known values 
    for (int i=0; i < readings.size(); i++) 
    { 
      double compareTemp = readings.get(i).getValue(ch); 
      if (compareTemp > targetTemperature) 
      { 
       System.out.println(readings.get(i).getTimestamp() + "is above target temp for channel " + ch); 
       return i; 
      } 
    } 
    System.out.println(readings.get(i).getTimestamp() + "Is not 
      above target temp for channel " + ch); 
    return -1; 
} 
+0

不正确:在没有找到元素的情况下返回0,并且在第一个元素符合条件的情况下返回0。 – DVarga

+0

这是正确的,更新谢谢! – AndyB

2

因为你的if语句是你的循环中,如果你的循环发生别跑? ==>表示你没有返回语句! 在你的循环中添加一个return语句,尽管你知道它不能仅仅因为你确定循环会运行而运行这个语句,但编译器不知道那个是

1

你的循环是不正确的:如果第一个元素不符合条件,该方法将在else分支返回,甚至没有检查列表中的其他要素。

您可以删除其他BRACH,并作出约定(如果没有项目被发现与指定条件javadoc注释,即返回-1)...

public int findRow(double targetTemperature, int ch) { 
    for (int i = 0; i < readings.size(); i++) { 
     if (readings.get(i).getValue(ch) > targetTemperature) 
      return i; 
    } 
    return -1; 
} 

...和您可以根据对发送方的返回值记录任何:

int channel = 2; 
int ind = findRow(35, channel); 
if (ind >= 0) 
    System.out.println(readings.get(ind).getTimestamp() + " is above target temp for channel " + channel); 
else 
    System.out.println("Nothing has been found"); 

使用流

相同:

public int findRow(double targetTemperature, int ch) { 
    return IntStream.range(0, readings.size()) 
      .filter(i -> readings.get(i).getValue(ch) > targetTemperature) 
      .findFirst() 
      .orElse(-1); 
}