Skip to content
Advertisement

Different Java Scanner for input of different types

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 Scanner(System.in);

System.out.print("Enter Age: ");
age = sc.nextInt();
System.out.print("Enter Name: ");
name= sc.nextLine();

With the aobe codes, I was not given a chance to enter the name. So normally I will declare 2 scanner objects as follows:

int age=0;
String name;
Scanner sc = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);    //2nd Scanner object

System.out.print("Enter Age: ");
age = sc.nextInt();
System.out.print("Enter Name: ");
name= sc2.nextLine();                    //Using 2nd Scanner Object

My question is: Is it necessary to declare multiple scanner objects to accept inputs of different types?? Am I doing the proper way as aobve?

I have this question in mind for years already. (Several questions in SO mention multiple scanner, but their questions only used one scanner object, so I am asking this today.)

Advertisement

Answer

@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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement