Home > Mobile >  Java Error when receiving multiple inputs in IntelliJ
Java Error when receiving multiple inputs in IntelliJ

Time:05-16

I'm having trouble receiving 2 user inputs back to back. When I run the code below, it doesn't register the 2nd line. If I receive it as int a = Integer.valueof(reader.nextLine()); it gives an error.

Basically it skips over second input. If I put a println between 2 inputs no there is no issue but this code works fine with other IDEs.

Is there a problem with IntelliJ or am I doing something wrong?

Scanner reader = new Scanner(System.in);

System.out.println("Input two strings");
String a = reader.nextLine();
String b = reader.nextLine();

System.out.println("you wrote "   a   " "   b);

Code as integer:
Code as integer

Error:
It's error

CodePudding user response:

As the documentation of the nextLine() method states

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. [...]

https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

Pressing the enter key corresponds to inputting two characters: a new line (\n) and a carriage return (\r). Both of these are line separators. When you type your first input and then press enter, the Scanner returns the first line, stops and then awaits for the second input (your second nextLine() invocation). However, since there is already a line terminator (the second line terminator left from the previous read), once you enter your second input, your scanner immediately halts at the beginning and returns an empty String.

What you need to do is to get rid of that "extra" line terminator character with a nextLine() placed in between the first and second read.

Scanner reader = new Scanner(System.in);

System.out.println("Input two strings");
String a = reader.nextLine();
reader.nextLine();
String b = reader.nextLine();

System.out.println("you wrote "   a   " "   b);

Alternatively, you can ask for the input with two print messages. In fact, the second print will move the Scanner's internal cursor forward (as the program has written some text on screen), skipping the second line terminator and retrieving your input correctly:

Scanner reader = new Scanner(System.in);

System.out.println("Input the first string");
String a = reader.nextLine();
System.out.println("Input the second string");
String b = reader.nextLine();

System.out.println("you wrote "   a   " "   b);
  • Related