我有一个名为 PlayGame
的类(class),并在main
中方法我有这段代码:
public class PlayGame {
public static void main(String args[]) {
while (true) {
System.out.println("Where would you like your adventure to begin? (Enter a number)\n");
System.out.println("1. Play the Game\n2. Quit the Game");
Scanner userInput = new Scanner(System.in);
String userAction;
try {
userAction = userInput.nextLine().trim();
if (userAction.equals("1")) {
pressPlay();
} else if (userAction.equals("2")) {
System.exit(0);
} else {
System.out.println("Sorry, your selection wasn't valid.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
这一切都很好,当用户输入 1 时,pressPlay()
被调用并继续执行下一个方法,该方法执行一些操作,主要是将内容打印到屏幕上。然而,当我离开 pressPlay()
方法并返回到此主方法,我开始在读取输入时出现错误:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at PlayGame.main(PlayGame.java:17)
你能告诉我如何解决这个问题吗?非常感谢!
编辑 - 我只是希望它返回到主方法中的 while 循环并再次请求 1 或 2,并获取有效的 1 或 2。我的代码一直到userAction = userInput.nextLine().trim();
离开 pressPlay()
后,无需等待第二次用户输入方法。
编辑 - pressPlay()
方法生成一个网格,玩家可以通过键入特定命令在其中移动。它有一个while (true) {
在其内部循环,以及 Scanner userInput = new Scanner(System.in);
它接受玩家的输入。如果玩家输入 quit,它会调用 while 循环的中断并返回到 main 方法,然后问题就会出现。
最佳答案
我已经成功解决了这个问题。
在我的主方法和 pressPlay()
方法中,我创建了单独的扫描仪,从 System.in
获取输入,这导致了问题,因为它不会不再需要从 main 方法获取输入。相反,我将扫描仪从主方法中取出,并将其放在 public class PlayGame {
之后,并在我的两个方法中使用相同的扫描仪,而不是单独的方法。
感谢 Jayamohan 和 Hossam 的意见(:
关于Java Scanner 获取输入,调用方法,然后返回读取更多输入不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15036445/