简体   繁体   English

关闭扫描程序会引发java.util.NoSuchElementException

[英]Closing a Scanner throws java.util.NoSuchElementException

I'm writing an RPG combat system from scratch in Java, ambitious right? 我正在用Java从头开始编写RPG战斗系统,雄心勃勃吧? Well, I'm having some trouble. 好吧,我遇到了麻烦。 This is my code: 这是我的代码:

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 线程“主”中的异常java.util.NoSuchElementException:找不到行
at java.util.Scanner.nextLine(Unknown Source) 在java.util.Scanner.nextLine(未知来源)
at Combat.turnChoice(Combat.java:23) 在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. 该类称为Combat,我只希望它提供一个战斗或运行或使用物品的选项,我首先尝试仅使用fight方法。 Please help, I'm kind of new to Java so don't make things too complicated if possible. 请帮助,我是Java的新手,所以如果可能的话,不要使事情变得太复杂。

When you are reading using Scanner from System.in , you should not close any Scanner instances because closing one will close System.in and when you do the following, NoSuchElementException will be thrown. 当您从System.in使用Scanner进行读取时,不应关闭任何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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM