简体   繁体   中英

Java Error when receiving multiple inputs in IntelliJ

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:
代码为整数

Error:
这是错误

As the documentation of the nextLine() method states

Advances this scanner past the current line and returns the input that was skipped. .[...]

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM