Java 在 IntelliJ 中接收多个输入时出错

Java Error when receiving multiple inputs in IntelliJ

我无法连续接收 2 个用户输入。当我 运行 下面的代码时,它没有注册第二行。如果我收到它作为 int a = Integer.valueof(reader.nextLine()); 它给出一个错误。

基本上它会跳过第二个输入。如果我在 2 个输入之间放置一个 println 没有问题,但是这段代码可以与其他 IDE 一起正常工作。

是 IntelliJ 有问题还是我做错了什么?

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

整数代码:

错误:

正如 nextLine() 方法的文档所述

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

按回车键对应输入两个字符:换行(\n)和回车return(\r)。这两个都是行分隔符。当您键入第一个输入然后按回车键时,第一行的 Scanner return 停止并等待第二个输入(您的第二个 nextLine() 调用)。但是,由于已经有一个行终止符(上一次读取留下的第二个行终止符),一旦您输入第二个输入,您的扫描仪会立即停止在开头并且 returns 是一个空的 String

你需要做的是去掉那个“额外的”行终止符,在第一次和第二次读取之间放置一个 nextLine()

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

或者,您可以使用两个打印消息请求输入。事实上,第二次打印会将 Scanner 的内部光标向前移动(因为程序已经在屏幕上写了一些文本),跳过第二行终止符并正确检索您的输入:

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