[英]While-loop termination
如果我注释掉那一行,则garbage = scan.nextLine();
,while循环将无限运行。 否则,事实并非如此。 我了解为什么如果只有print命令,它将无限地运行,但是我不完全理解garbage
变量的包含是如何阻止它无限运行的。 有人可以解释一下吗?
import java.util.Scanner;
public class TypeSafeReadInteger
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
String garbage;
System.out.print("Enter age as an integer > ");
while (! scan.hasNextInt())
{
garbage = scan.nextLine();
System.out.print("\nPlease enter an integer > ");
}
int age = scan.nextInt();
System.out.println("Your age is " + age);
}
}
garbage
只是一个变量,while循环的“停止”是nextLine()
它是一种等待用户输入的方法。 直到您的用户使用键盘输入内容并将输入内容保存到garbage
变量后,一段时间才会继续。
要修复您的代码:
while (!scan.hasNextInt())
{
scan.nextLine(); // the order of the lines inside the loop makes the difference!
System.out.print("\nPlease enter an integer > ");
// when you perform nextLine() here - you reach the beginning of the loop
// without a token in the scanner - so you end up looping forever
}
int age = scan.nextInt();
顺便说一句-从上面的示例中可以看到, garbage
是多余的。
如果用户输入整数,则一切正常。 如果它们不garbage = scan.nextLine();
,那么您将得到无限循环而没有garbage = scan.nextLine();
线是由于Scanner类的工作方式。
当您执行诸如scan.hasNextInt();
,实际上没有从输入中读取任何字符。 因此,如果用户根据您的提示输入了类似“ cat”的内容,那么该输入将在该单词的第一个字母之前暂停。 因为要循环直到输入中有整数,所以不会再读取任何内容,并且将无限循环,因为“ cat”仅位于输入缓冲区中。
通过添加scan.nextLine()
您将导致扫描器丢弃所有内容,直到用户按下<enter>并可以处理其他输入为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.