2014-04-02 59 views
0

內我有簡單的文本文件,它看起來是這樣的:java如果號碼間隔

2-4 
3-8 
5-6 
1-9 

我要檢查,如果通過數字是這些區間內。目前,我有這樣的事情:

int first = 2; //passed to the method 
int second = 4; // passed to the method 

while ((newLine = bufferReader.readLine()) != null) { 
    String[] result = newLine.split("-"); 

    int numberOne = Character.getNumericValue(result[0]); 
    int numberTwo = Character.getNumericValue(result[1]); 

    if ((first >= numberOne && first <= numberTwo) && (second >= numberOne && second <= numberTwo)) { 
     System.out.println("Numbers are between " + numberOne + " and " + numberTwo); 
    } 
} 

現在它將打印結果是這樣的:

Numbers are between 2 and 4 
Numbers are between 1 and 9 

我想什麼要打印的是僅此:Numbers are between 2 and 4

這裏是一些例子:

passing 1 and 2 would print out: Numbers are between 1 and 9 
passing 5 and 6 would print out: Numbers are between 5 and 6 
passing 4 and 8 would print out: Numbers are between 3 and 8 

希望你的想法。

+0

那麼,告訴我們背後的想法是什麼?你只想得到第一個結果?如果'if'中的'break'語句如何? – bobbel

+0

最簡單的方法將是你的時間間隔存儲在數組中,並希望其返回的順序進行排序 - 從最窄到最寬的。然後迭代這些數組元素,並將輸入與較低值和較高值進行比較,如果它們符合退出迭代的話。 –

+0

目前尚不清楚,你的算法應該做的 - 這是完全正確的,它打印出所有的有效範圍,因爲2和4均爲2和4之間以及1和9之間 –

回答

0

如果輸入的排序,你只需要休息有效結果的循環。

否則,你存儲列表中的所有您的有效結果和循環結束後,您只需選擇在結果列表中最小的範圍內。

... 
    List<int[]> resultList = new ArrayList<int[]> 
    while ((newLine = bufferReader.readLine()) != null) { 
     String[] result = newLine.split("-"); 
     int numberOne = Character.getNumericValue(result[0]); 
     int numberTwo = Character.getNumericValue(result[1]); 
     if ((first >= numberOne && first <= numberTwo) && (second >= numberOne && second <= numberTwo)) { 
      resultList.add(new int[2]{numberOne,nunumberTwo}); 
     } 
    } 
    if(!resultList.isEmpty()){ 
     int[] smallestInterval = null; 
     int minInterval = 0; 
     for(int[] result : resultList){ 
      int inerval = result[1]-result[0] 
      if(smallestInterval==null || inerval < smallestInterval){ 
       minInterval = inerval; 
       smallestInterval= result; 
      } 
     } 
     System.out.println("Numbers are between " + smallestInterval[0] + " and " + smallestInterval[1]); 
    } 
0

你檢查狀況良好。 只有你需要打破;從循環中找到所提供的值所在的匹配數字。

0

試試這個。它應該只打印第一行。

if ((first >= numberOne && first <= numberTwo) && (second >= numberOne && second <=  numberTwo)) { 
     System.out.println("Numbers are between " + numberOne + " and " + numberTwo); 
     break; 
}