我试图在按下控制台中的 Enter 键后调用一个方法。问题是从我第二次按 Enter 时调用该方法。第一次按下 Enter 后如何调用我的方法?
public void read() {
Scanner scanner = new Scanner(System.in);
System.out.println("Press Enter to continue");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
if (scanner.hasNextLine()) {
this.win();
}
}
public void win() {
if (true) {
this.read();
}
}
最佳答案
等待 Enter 按下的代码在 Scanner
看到该字符之前从输入流中“窃取”该字符。因此,第一个 '\n'
被 System.in.read()
行消耗。
当您基于控制台调用 Scanner
的 scanner.hasNextLine()
时,代码会阻塞以查看最终用户是否输入一行或终止流。 hasNextLine
方法需要返回第二个 '\n'
。
您可以通过删除对 System.in.read() 的调用并调用 getNextLine() 来在下次调用之前使用输入来解决此问题:
public void read() {
Scanner scanner = new Scanner(System.in);
System.out.println("Press Enter to continue");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
if (scanner.hasNextLine()) {
scanner.nextLine(); // Remove '\n' from the buffer
this.win();
}
}
关于Java 扫描仪从第二次开始工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47638501/