2017-04-24 128 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); 
}