更新时间:2023-01-14 13:50:59
好吧,根据
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()