java - 无休止的循环-while循环内的scanner.hasNextInt()
问题描述
问题在代码的注释中,对不起,我认为它更整洁,因为流程很重要,我想......
import java.util.Scanner;
public class ReadingUserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please, enter 10 numbers, for example, from 1 to 100!");
int number = 0;
int total = 0;
int counter = 0;
while (counter < 10) {
System.out.println("Enter number #" + (counter + 1));
boolean hasNextInt = scanner.hasNextInt(); // here we open the prompt for user to enter the value/s*
// internally, we are ready to check if the input is going to be int
// user types the value/s and clicks enter
// let's presume, he/she typed '3'
// internally, user's input is like that (if Windows**) - '3\n'
// because when user presses Enter - \n is added to what he/she typed
if (hasNextInt) { // the app checks, ant it's int, that is, it's OK (true)
number = scanner.nextInt(); //here the application grabs user's input
//but, internally, it grabs only '3', because 'nextInt()' grabs only ints
// and doesn't "care" about the new feed/line - \n - character
// so, '\n' is left in Scanner's buffer!
counter++;
total += number;
} else {
System.out.println("Invalid Input! Try again!");
}
//scanner.nextLine(); // let's presume, this commented line, on the left of this line of comment, is absent in our code
// the flow of our code goes to boolean hasNextInt = scanner.hasNextInt();
// and again internally, we are ready to check if the input is going to be int
// and again the user is prompted (by a blinking cursor) to type his/her input
// and at this moment user types either a numeric again or a non-numeric character (a letter/letters)
// let's presume he/she is typing '4'
// and again, internally, user's input is actually like that (if Windows**) - '4\n'
// but scanner.hasNextInt() says 'OK', for the int is there! and it doesn't care about '\n'
//
// Now, let's presume that user (this time or next time) types 'a'
// Do we actually have 'a\n' ???
// and this time scanner.hasNextInt() says 'Alarm' - 'false'
// thus the input doesn't go to number = scanner.nextInt();
// So, does it mean that 'a\n' (or 'a') remains in Scanner's buffer???
// and it (scanner.hasNextInt()) kicks us to 'else'
// and we have an endless loop:
//Invalid Input! Try again!
//Enter number #...
//Invalid Input! Try again!
//Enter number #...
//Invalid Input! Try again!
//Enter number #...
//Invalid Input! Try again!
//Enter number #...
//Invalid Input! Try again!
//Enter number #...
//Invalid Input! Try again!
//Enter number #...
//Invalid Input! Try again!
//Enter number #...
//Why?
// Is there still 'a' (or 'a\n') and scanner.hasNextInt() throws the flow to 'else' endlessly,
// because "The scanner does not advance past any input"* ???
//
// or: there's only '\n', and again its not int, and we result in endless loop ???
// And finally, is that a different case? https://www.youtube.com/watch?v=_xqzmDyLWvs
// And PS: Is there anything wrong in my description in the comments?
// So what do we 'consume' by scanner.nextLine(); ???
}
scanner.close();
System.out.println("Thank you, your total is " + total);
}
}
// *这是来自 Oracle :( https://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt%28%29 )
"hasNextInt
公共布尔 hasNextInt()
如果此扫描器输入中的下一个标记可以使用 nextInt() 方法解释为默认基数中的 int 值,则返回 true。扫描仪不会超过任何输入。”
// ** https://knowledge.ni.com/KnowledgeArticleDetails?id=kA00Z0000019KZDSA2
解决方案
而是创建另一个扫描仪对象,忘记内部缓冲区中剩下的内容。
public class ReadingUserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please, enter 10 numbers, for example, from 1 to 100!");
int number = 0;
int total = 0;
int counter = 0;
while (counter < 10) {
System.out.println("Enter number #" + (counter + 1));
boolean hasNextInt = scanner.hasNextInt();
if (hasNextInt) {
number = scanner.nextInt();
counter++;
total += number;
} else {
System.out.println("Invalid Input! Try again!");
scanner = new Scanner(System.in);
}
}
scanner.close();
System.out.println("Thank you, your total is " + total);
}
}
推荐阅读
- python - Pygame如何让球发生碰撞
- python - How do I fix this 'No file or directory' error
- mysql - 如何使用下面的 whereHas like sql 查询创建雄辩的范围?
- c++ - 如何将 ROS AudioData 消息写入 wav 文件?
- php - 执行 PHP 脚本来处理 Apache2 的 ErrorDocument 500
- mongodb - 如果我在重命名 MongoDB 集合时发送查询会发生什么?
- python - 如何在python的正则表达式模块中获取多个以字符串开头和以字符串结尾的字符串?
- python - 如何在早晚之间获得频繁的时间戳?
- python - 如何通过鼠标单击并拖动来选中或取消选中“PySide2 QStandardItemModel”中的 QStandrdItem 复选框?
- vuetify.js - Vuetify.js:当我关闭并再次打开时,v-dialog 不起作用