Closing a Scanner throws java.util.NoSuchElementException

15,564

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!
Share:
15,564
user2172205
Author by

user2172205

Updated on July 27, 2022

Comments

  • user2172205
    user2172205 almost 2 years

    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.

  • user2172205
    user2172205 about 11 years
    Wouldn't that cause a memory leak?
  • mostruash
    mostruash about 11 years
    System.in is closed by the JVM and you should not close it. Don't worry about it. Scanners are just buffer readers.
  • Ahmed Shendy
    Ahmed Shendy over 4 years
    @mostruash, so we shouldn't close any scanner, and whenever the app is closed then all scanners will be cleared from the memory, right?