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();
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();
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.
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();
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With