11

I am trying to input values of certain string and integer variables in Java. But if I am taking the input of string after the integer, in the console the string input is just skipped and moves to the next input.

Here is the code

String name1;
int id1,age1;

Scanner in = new Scanner(System.in);

//I can input name if input is before all integers

System.out.println("Enter id");
id1 = in.nextInt();


System.out.println("Enter name");       //Problem here, name input gets skipped
name1 = in.nextLine();

System.out.println("Enter age");
age1 = in.nextInt();
bhanu
  • 383
  • 2
  • 4
  • 17

3 Answers3

38

This is a common problem, and it happens because the nextInt method doesn't read the newline character of your input, so when you issue the command nextLine, the Scanner finds the newline character and gives you that as a line.

A workaround could be this one:

System.out.println("Enter id");
id1 = in.nextInt();

in.nextLine();   // skip the newline character

System.out.println("Enter name");
name1 = in.nextLine();

Another way would be to always use nextLine wrapped into a Integer.parseInt:

int id1;
try {
    System.out.println("Enter id");
    id1 = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
    e.printStackTrace();
}
System.out.println("Enter name");
name1 = in.nextLine();

Why not just Scanner.next() ?

I would not use Scanner.next() because this will read only the next token and not the full line. For example the following code:

System.out("Enter name: ");
String name = in.next();
System.out(name);

will produce:

Enter name: Mad Scientist
Mad

It will not process Scientist because Mad is already a completed token per se. So maybe this is the expected behavior for your application, but it has a different semantic from the code you posted in the question.

enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
2

This is your updated working code.

 package myPackage;

    import java.util.Scanner;

    public class test {

        /**
         * @param args
         */
        public static void main(String[] args) {
            String name1;
            int id1,age1;

            Scanner in = new Scanner(System.in);

            //I can input name if input is before all integers

            System.out.println("Enter id");
            id1 = in.nextInt();


            System.out.println("Enter name");       //Problem here, name input gets skipped
            name1 = in.next();

            System.out.println("Enter age");
            age1 = in.nextInt();

        }

    }
sTg
  • 4,313
  • 16
  • 68
  • 115
1

May be you try this way..

Instead of this code

       System.out.println("Enter name");       //Problem here, name input gets skipped
       name1 = in.nextLine();

try this

       System.out.println("Enter name");      
       name1 = in.next();
Rookie007
  • 1,229
  • 2
  • 18
  • 50