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();
Answer
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.
No comments:
Post a Comment