关闭扫描仪抛出 java.util.NoSuchElementException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15423519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:32:12  来源:igfitidea点击:

Closing a Scanner throws java.util.NoSuchElementException

javastringexceptionelement

提问by user2172205

I'm writing an RPG combat system from scratch in Java, ambitious right? Well, I'm having some trouble. This is my code:

我正在用 Java 从头开始​​编写 RPG 战斗系统,雄心勃勃,对吧?好吧,我遇到了一些麻烦。这是我的代码:

void turnChoice() {
    System.out.println("What will you do? Say (Fight) (Run) (Use Item)");
    Scanner turnChoice = new Scanner(System.in);
    switch (turnChoice.nextLine()) {
        case ("Fight"):
            Combat fighting = new Combat();
            fighting.fight();
        default:
    }

    turnChoice.close();
}

When it hits that point in the code I get:

当它到达代码中的那个点时,我得到:

What will you do? Say (Fight) (Run) (Use Item)
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Combat.turnChoice(Combat.java:23)

你会怎么做?Say (Fight) (Run) (Use Item)
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Combat.turnChoice(Combat.java:23)

The class is called Combat, I just want it to give an option to fight or run or use items, I'm trying just the fight method first. Please help, I'm kind of new to Java so don't make things too complicated if possible.

这个类叫做 Combat,我只是想让它提供一个选项来战斗或运行或使用物品,我首先尝试战斗方法。请帮忙,我对 Java 有点陌生,所以如果可能的话不要把事情弄得太复杂。

回答by mostruash

When you are reading using Scannerfrom System.in, you should not close any Scannerinstances because closing one will close System.inand when you do the following, NoSuchElementExceptionwill be thrown.

当您使用Scannerfrom阅读时System.in,您不应该关闭任何Scanner实例,因为关闭一个将关闭,System.in而当您执行以下操作时,NoSuchElementException将被抛出。

Scanner sc1 = new Scanner(System.in);
String str = sc1.nextLine();
...
sc1.close();
...
...
Scanner sc2 = new Scanner(System.in);
String newStr = sc2.nextLine();      // Exception!