0

i was practicing scanner usage and syntax and below is the code i wrote, where I am trying to take 4 inputs from the user :

    Scanner s= new Scanner(System.in);
    
    int a = s.nextInt();// taking an integer as input, it works fine.
    String b = s.nextLine();//was supposed to take a string input, but not working
    String c=s.nextLine();//takes a string as input from user
    String d=s.nextLine();//takes another string as input from user

    System.out.println("integer entered: "+a);
    System.out.println("first string entered: "+b);
    System.out.println("second string entered: "+c);
    System.out.println("third string entered: "+d);

but the user is able to give only 3 inputs, the first integer and other two string inputs and by printing the values of these 4 variables, it is clear that input for first string String b is skipped.I then tried to rearrange the sequence in which the input was taken, i.e,

String b = s.nextLine();//takes a string input
int a = s.nextInt();// taking an integer as input
String c=s.nextLine();//was supposed to take a string as input from user
String d=s.nextLine();//takes another string as input from user

in this case, the input for the second string String cis skipped. So, is it because of the integer input that skips the next string input?

Siddhant
  • 487
  • 1
  • 5
  • 14
  • You've read the integer of the first line with `Scanner.nextInt()`, but not the rest of the line it was on : `.nextInt()` doesn't consume the linefeed. Add an extra `.nextLine()` after the `.nextInt()` to consume and discard the (empty) rest of the first line. – Aaron Mar 19 '20 at 18:59
  • Or ParseInt the nextLine()... ;-) – JGFMK Mar 19 '20 at 19:00

1 Answers1

1

This is a common question.


Fixed code

Scanner s= new Scanner(System.in);
int a = s.nextInt();
s.nextLine();
System.out.print("Enter a string: ");
String b = s.nextLine();
System.out.print("Enter another string: ");
String c=s.nextLine();
System.out.print("Enter one more string: ");
String d=s.nextLine();

System.out.println(a+"\n"+b+d+c);

Ref: Scanner is skipping nextLine() after using next() or nextFoo()?

RRIL97
  • 852
  • 2
  • 9