0

I am trying to take multiple input from user of different classes, if I am working only with String type my code work fine but when I am using any other class like int, flot or any other it ignore the next String input why is this happening can any one help me.

Scanner obj = new Scanner(System.in);
String a,b,c;
int x,y,z;
System.out.print("Enter any string: ");
a = obj.nextLine();
System.out.print("enter any int: ");
x = obj.nextInt();                                                                                             
System.out.print("Enter any thing: ");    //after getting input for int it ignore next string 
b = obj.nextLine();                       input
System.out.print("Enter any thing: ");
c = obj.nextLine();

1 Answers1

0

After you call obj.nextInt(), you still have the EOL from the Return that the user pressed after entering the number sitting in the input buffer, because nextInt() only read the numeric characters. You have to skip those characters by calling obj.nextLine() and just ignoring the result. Then you can go on and ask for additional input from the user.

This gives you what you expected:

Scanner obj = new Scanner(System.in);
String a,b,c;
int x,y,z;
System.out.print("Enter any string: ");
a = obj.nextLine();
System.out.print("enter any int: ");
x = obj.nextInt();
obj.nextLine();
System.out.print("Enter any thing: ");    //after getting input for int it ignore next string
b = obj.nextLine();
System.out.print("Enter any thing: ");
c = obj.nextLine();

System.out.println("1: " + b);
System.out.println("2: " + c);

Sample run:

Enter any string: anystring
enter any int: 12345
Enter any thing: anything
Enter any thing: more anything
1: anything
2: more anything
CryptoFool
  • 15,463
  • 4
  • 16
  • 36