Java 在扫描仪中查找整数范围 public int rangeInScanner(扫描流){ int max=stream.nextInt(); int min=stream.nextInt(); while(stream.hasNextInt()){ if(stream.nextInt()>max){ max=stream.nextInt(); } if(stream.nextInt()最大值) 最大值=当前值; 如果(当前
为什么我不能让它工作呢。假设扫描器流=新扫描器(“5,4,3,2,1”); 我想把这个退4。我想应该是Java 在扫描仪中查找整数范围 public int rangeInScanner(扫描流){ int max=stream.nextInt(); int min=stream.nextInt(); while(stream.hasNextInt()){ if(stream.nextInt()>max){ max=stream.nextInt(); } if(stream.nextInt()最大值) 最大值=当前值; 如果(当前,java,range,Java,Range,为什么我不能让它工作呢。假设扫描器流=新扫描器(“5,4,3,2,1”); 我想把这个退4。我想应该是 public int rangeInScanner(Scanner stream) { int max = stream.nextInt(); int min = stream.nextInt(); while (stream.hasNextInt()){ if (stream.nextInt() > max) { max
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;
}
public int rangeInScanner(扫描流){
int max=stream.nextInt();
int最小值=最大值;
while(stream.hasNextInt()){
int curr=stream.nextInt();
如果(当前>最大值)
最大值=当前值;
如果(当前<分钟)
最小值=当前值;
}
返回最大-最小值;
}
编辑
您缺少所需比较的一半,并且可能会生成异常。如果有奇数个整数,将抛出一个Yep,扫描器是有状态的。每次调用nextInt()时,您都在移动到下一个元素,而不仅仅是“偷看”。@DavidATarris:感谢您如此清晰地表达了这个概念。我曾短暂地试图找到所需的英文措辞,但我失败了……非常感谢。所以基本上我需要先存储下一个值,然后再进行比较,否则它就太超前了?
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;
}