Scanner.hasNext上的无限循环,从文件中读取 [英] Infinite loop on Scanner.hasNext, reading from a file
问题描述
我显然在上面临无限循环,而(input.hasNext())
,如下面的代码
I'm apparently facing an infinite loop on while(input.hasNext())
, as in following code
File file = new File("data.txt");
Scanner input = new Scanner(file);
int sum = 0;
while (input.hasNext()) {
if (input.hasNextInt()) {
sum += input.nextInt();
}
}
System.out.println(sum);
一些相关问题解释了为什么如果输入流是 System,它总是返回true。在
中,但是我正在扫描文件
。
Some related questions explain why it always returns true if input stream is System.in
, however I'm scanning through a File
.
请告诉我我错了。
我正在尝试计算唯一整数值的总和(空格分隔的位置)。
I'm attempting to calculate the sum of unique integer values (space delimited where they occur).
修改:
获得的经验教训,
input.hasNext()
不会将指针移动到下一行,因此扫描程序不会超过任何输入。正如本问题的答案以及此处所述。
Lesson learned,
input.hasNext()
does not move the pointer to the next line and thus the scanner does not advance past any input. As explained in answers to this question as well as here .
推荐答案
好吧,根据
while(input.hasNext()) {
if(input.hasNextInt()) {
sum += input.nextInt();
}
}
如果此令牌,您的扫描仪将不会使用下一个令牌不是 int
,你可以使用类似
Your scanner will not consume the next token if this token isn't an int
, you can hilight this behavior with something like
int k=0;
while(input.hasNext()) {
if(input.hasNextInt()) {
sum += input.nextInt();
} else {
System.err.println("What ? It's not an integer...");
if ( k < 1 ) {
System.err.println("I'm gonna try again !");
k++;
} else {
System.err.println("'"+input.next()+"' it's definitively not an integer");
k=0;
}
}
}
最后,有很多解决方案,例如:
Finally, there are many solutions, for example :
- 修改输入文件删除所有非整数标记
- 消耗带
的非整数令牌Scanner :: next()
- Sanjeev的回答
这篇关于Scanner.hasNext上的无限循环,从文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!