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

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

问题描述

我在Java中从头开始编写一个RPG战斗系统,雄心勃勃吗?嗯,我有麻烦了这是我的代码:

  void turnChoice(){
System.out.println(你会做什么?说(战斗)(运行)(使用项目));
扫描仪turnChoice =新的扫描仪(System.in);
switch(turnChoice.nextLine()){
case(Fight):
战斗战斗=新战斗();
fighting.fight();
默认值:
}

turnChoice.close();
}

当它在代码中点击了这一点:


你会做什么?说(战斗)(运行)(使用项目)

线程main中的异常java.util.NoSuchElementException:找不到行

在java.util.Scanner.nextLine(未知来源)
在Combat.turnChoice(Combat.java:23)


该类被称为Combat,I只是想让它给一个选项来战斗或运行或使用项目,我只是尝试战斗方法。请帮助,我是Java的新手,所以不要让事情太复杂,如果可能的话。

解决方案

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

  Scanner sc1 = new Scanner(System.in); 
String str = sc1.nextLine();
...
sc1.close();
...
...
扫描仪sc2 =新扫描仪(System.in);
String newStr = sc2.nextLine(); //异常!


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:

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)

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.

解决方案

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天全站免登陆