当我运行以下代码时:
类Startup
(由main()
调用):
import java.util.ArrayList;
public class Startup {
public void start() {
// Build rooms
final int WIDTH = 2;
final int HEIGHT = 2;
Room[][] room = new Room[WIDTH][HEIGHT];
Rooms.build(room, WIDTH, HEIGHT);
int x = 0;
int y = 0;
// Print starting room description
Rooms.print(room, x, y);
// Start game loop
boolean playing = true;
while (playing) {
// Get user input
String input = Input.getInput();
System.out.println(input);
// Movement commands
if (input.equals("n")) {
if (y > 0) {
y--;
Rooms.print(room, x, y);
} else {
System.out.println("You can't go that way.");
}
}
}
}
}
类输入
:
import java.util.Scanner;
public class Input {
public static String getInput() {
System.out.print("> ");
try(Scanner in = new Scanner(System.in)) {
String input = in.nextLine();
input.toLowerCase();
return input;
}
}
}
我总是会得到这个NoSuchElementException
:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Input.getInput(Input.java:11)
at Startup.start(Startup.java:36)
at Driver.main(Driver.java:11)
如果删除 start()
中的移动命令部分,则一切正常。但是当包含该部分时,总是会调用该异常,这让我认为它有问题。但我的问题是:出了什么问题?
最佳答案
每次调用 getInput
时,您都会创建一个新的扫描器。不幸的是,您每次都会关闭它:
try(Scanner in = new Scanner(System.in)) {
String input = in.nextLine();
input.toLowerCase();
return input;
}
此构造称为“尝试使用资源”。它创建了 Scanner
,它是一个 Closeable
对象,并且在 try
block 的末尾,它关闭它。
这意味着扫描仪后面的输入流也被关闭。
一旦关闭流,就无法重新打开。该流的每个输入请求都将返回“文件结束”条件。因此,每次您在同一个(关闭的)System.in 上打开第一个扫描仪之后的新扫描仪时,您都会得到一个位于“文件末尾”的空扫描仪。
您只需打开扫描仪一次即可。然后对于程序的其余部分,从同一个打开的扫描仪读取。为此,您要么必须将所有程序放在 try-with-resources 中,要么根本不使用 try-with-resources。
关于java - 扫描仪无法读取我的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41381171/