[英]some questions about java Scanner
enter image description here }在此处输入图片说明}
Why does the code on line 6 have the same effect on line 8?为什么第6行的代码和第8行的效果一样? Is there no distinction between the starting point of this while loop?
这个while循环的起点没有区别吗?
Also, you should follow this tips to use the Scanner
properly:此外,您应该按照以下提示正确使用
Scanner
:
Mixing any nextXXX
method with nextLine
from the Scanner
class for user input, will not ask you for input again but instead result in an empty line read by nextLine
.将任何
nextXXX
方法与来自Scanner
类的nextLine
混合用于用户输入,不会再次要求您输入,而是导致nextLine
读取空行。
To prevent this, when reading user input, always only use nextLine
.为了防止这种情况,在读取用户输入时,始终只使用
nextLine
。 If you need an int
, do int value = Integer.parseInt(scanner.nextLine());
如果您需要
int
,请执行int value = Integer.parseInt(scanner.nextLine());
instead of using nextInt
.而不是使用
nextInt
。
Assume the following:假设如下:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age:");
int age = sc.nextInt();
System.out.println("Enter your name:");
String name = sc.nextLine();
System.out.println("Hello " + name + ", you are " + age + " years old");
When executing this code, you will be asked to enter an age, suppose you enter 20
.执行此代码时,系统会要求您输入年龄,假设您输入
20
。 However, the code will not ask you to actually input a name and the output will be:但是,代码不会要求您实际输入名称,输出将是:
Hello , you are 20 years old.
The reason why is that when you hit the enter button, your actual input is原因是当你按下回车键时,你的实际输入是
20\n
and not just 20
.而不仅仅是
20
。 A call to nextInt
will now consume the 20
and leave the newline symbol \\n
in the internal input buffer of System.in
.对
nextInt
的调用现在将消耗20
并将换行符\\n
留在System.in
的内部输入缓冲区中。 The call to nextLine
will now not lead to a new input, since there is still unread input left in System.in
.对
nextLine
的调用现在不会导致新的输入,因为System.in
仍有未读的输入。 So it will read the \\n
, leading to an empty input.所以它会读取
\\n
,导致一个空的输入。
So every user input is not only a number, but a full line .因此,每个用户输入不仅是一个数字,而且是整行。 As such, it makes much more sense to also use
nextLine()
, even if reading just an age.因此,即使只阅读一个年龄,也使用
nextLine()
更有意义。 The corrected code which works as intended is:按预期工作的更正代码是:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age:");
// Now nextLine, not nextInt anymore
int age = Integer.parseInt(sc.nextLine());
System.out.println("Enter your name:");
String name = sc.nextLine();
System.out.println("Hello " + name + ", you are " + age + " years old");
The nextXXX
methods, such as nextInt
can be useful when reading multi-input from a single line. nextXXX
方法(例如nextInt
在从单行读取多输入时很有用。 For example when you enter 20 John
in a single line.例如,当您在一行中输入
20 John
时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.