【发布时间】:2021-10-20 19:39:35
【问题描述】:
我有两个 do-while 循环用于进行自定义输入验证。问题是它会自动进入下一个do-while 循环。正确插入名称后,我必须添加一个新的nextLine():name = scanner.nextLine();
当光标停留在那里时,我知道nextInt() 的“故障”,您必须调用nextLine() 才能继续。来源:https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/
但事实并非如此。我显然错过了一些东西......
String name = "";
boolean flag_name= false;
do{
System.out.print("Name: ");
if(scanner.hasNextInt()){
System.out.println(scanner.nextInt() + " That's not a valid name...\n");
scanner.nextLine();
}else{
name = scanner.nextLine();
flag_name = true;
}
}while(!flag_name);
int age = 0;
boolean good_age = false;
do {
System.out.print("Age: ");
if (!scanner.hasNextInt()){
System.out.println("That's not a valid age.");
}else if(scanner.nextInt() <= 3 || scanner.nextInt() >= 125) {
System.out.println("You must be over 3yo.");
scanner.nextLine();
}else{
age = Integer.parseInt(scanner.nextLine());
good_age = true;
}
}while (!good_age);
输出:
Name: mark
Age: 'mark' That's not a valid age.
Age:
【问题讨论】:
-
自动进入next do while循环是什么意思?你的意思是连续迭代开始了吗?
-
scanner.nextInt() <= 3 || scanner.nextInt() >= 125这是不对的!如果第一个条件为假,您将再次执行scanner.nextInt()。相反,只需在int val = scanner.nextInt()之类的变量中读取它并检查val <= 3 || val >= 125 -
您能补充一下您是如何创建此扫描仪的吗?我在这段代码中看到了许多不一致的地方。您可以尝试在扫描仪上阅读 java doc:docs.oracle.com/javase/8/docs/api/java/util/Scanner.html,也可以参考此示例了解如何从命令行读取:javarevisited.blogspot.com/2012/12/…
-
在你更正@AppleCiderGuy 在他的第二条评论中提到的内容之后,你还会遇到另一个问题,它可能每周至少出现一次 StackOverflow。 using nextLine after nextInt or similar