我有一个简单的文本文件,如下所示:
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 :(得分:0)
你检查条件没问题。 只有你需要打破;一旦找到提供的值所在的匹配数字,就从循环开始。
答案 1 :(得分:0)
试试这个。它应该只打印第一行。
if ((first >= numberOne && first <= numberTwo) && (second >= numberOne && second <= numberTwo)) {
System.out.println("Numbers are between " + numberOne + " and " + numberTwo);
break;
}
答案 2 :(得分:0)
如果输入已排序,您只需要打破有效结果的循环。
否则,您将所有有效结果存储在List中,并且在循环结束后,您只需选择结果列表中的最小范围。
...
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]);
}