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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With