简体   繁体   中英

some questions about java Scanner

enter image description here }

Why does the code on line 6 have the same effect on line 8? Is there no distinction between the starting point of this while loop?

Also, you should follow this tips to use the Scanner properly:

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 .

To prevent this, when reading user input, always only use nextLine . If you need an int , do int value = Integer.parseInt(scanner.nextLine());

instead of using 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 . 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 . A call to nextInt will now consume the 20 and leave the newline symbol \\n in the internal input buffer of System.in . The call to nextLine will now not lead to a new input, since there is still unread input left in System.in . So it will read the \\n , leading to an empty input.

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. 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. For example when you enter 20 John in a single line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM