內我有簡單的文本文件,它看起來是這樣的: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
希望你的想法。
那麼,告訴我們背後的想法是什麼?你只想得到第一個結果?如果'if'中的'break'語句如何? – bobbel
最簡單的方法將是你的時間間隔存儲在數組中,並希望其返回的順序進行排序 - 從最窄到最寬的。然後迭代這些數組元素,並將輸入與較低值和較高值進行比較,如果它們符合退出迭代的話。 –
目前尚不清楚,你的算法應該做的 - 這是完全正確的,它打印出所有的有效範圍,因爲2和4均爲2和4之間以及1和9之間 –