关闭 Scanner 会抛出 java.util.NoSuchElementException [英] Closing a Scanner throws java.util.NoSuchElementException

查看:33
本文介绍了关闭 Scanner 会抛出 java.util.NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing an RPG combat system from scratch in Java, ambitious right? 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:

你会做什么?说(战斗)(跑)(使用物品)
线程主"java.util.NoSuchElementException 中的异常:未找到行
在 java.util.Scanner.nextLine(未知来源)
在 Combat.turnChoice(Combat.java:23)

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)

这个类叫做Combat,我只是想让它可以选择战斗或运行或使用物品,我先尝试战斗方法.请帮忙,我是 Java 新手,所以如果可能的话,不要把事情弄得太复杂.

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.

推荐答案

使用 System.in 中的 Scanner 阅读时,不应关闭任何 Scanner 实例,因为关闭一个将关闭 System.in 并且当您执行以下操作时,将抛出 NoSuchElementException.

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.

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

这篇关于关闭 Scanner 会抛出 java.util.NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆