Closing the scanner raises a java.util.NoSuchElementException

Am I writing an RPG combat system from scratch in Java, ambitious? Well, I have a problem. 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 gets to this point in the code, I get:

What are you going to do? Say (Combat) (Run) (Use item)
Exception in thread "main" java.util.NoSuchElementException: row not 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 the opportunity to fight, launch or use elements, first I try to use the battle method. Please help, I'm new to Java, so don't make things too complicated if possible.

+6
source share
1 answer

When you read using Scanner from System.in , you should not close any instances of Scanner , because closing will be closed by System.in , and when you do the following, NoSuchElementException will be NoSuchElementException .

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

All Articles