Different Java Scanner for input of different types

后端 未结 5 477
不思量自难忘°
不思量自难忘° 2021-01-16 06:40

Imagine the following scanario: I have a program which ask for an integer input, followed by a String input.

int age=0;
String name;
Scanner sc = new Scanne         


        
5条回答
  •  醉梦人生
    2021-01-16 07:02

    @skiwi is right about only using one Scanner, so you're doing that right. The reason it doesn't work is that nextInt() consumes all characters that make up the integer, but it does not touch the end-of-line character. So when nextLine() is called, it sees that there are no characters before the end-of-line character, so it thinks that an empty line was entered, and you get an empty String back. However, nextLine() does consume the end-of-line character, so if you call sc.nextLine(); once before you do name = sc.nextLine();, it should work.

提交回复
热议问题