public int rangeInScanner(Scanner stream) {
int max = stream.nextInt();
int min = stream.nextInt();
while (stream.hasNextInt()){
if (stream.nextInt() > max) {
max = stream.nextInt();
}
if (stream.nextInt() < min) {
min = stream.nextInt();
}
}
return max - min;
}
为什么我不能让它工作。让我们说Scanner stream = new Scanner(“5,4,3,2,1”); 我想让它返回4。
答案 0 :(得分:1)
我认为应该是
public int rangeInScanner(Scanner stream) {
int max = stream.nextInt();
int min = max;
while (stream.hasNextInt()){
int curr = stream.nextInt();
if (curr > max)
max = curr;
if (curr < min)
min = curr;
}
return max - min;
}
修改的
您缺少一半所需的比较,也可能产生异常。如果存在奇数个整数,nextInt将抛出NoSuchElementException