Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing a Scanner throws java.util.NoSuchElementException

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.

like image 422
user2172205 Avatar asked Mar 15 '13 02:03

user2172205


1 Answers

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!
like image 189
mostruash Avatar answered Sep 30 '22 19:09

mostruash