Reputation: 130
I have a class called PlayGame
, and in the main
method I have this chunk of code:
public class PlayGame {
public static void main(String args[]) {
while (true) {
System.out.println("Where would you like your adventure to begin? (Enter a number)\n");
System.out.println("1. Play the Game\n2. Quit the Game");
Scanner userInput = new Scanner(System.in);
String userAction;
try {
userAction = userInput.nextLine().trim();
if (userAction.equals("1")) {
pressPlay();
} else if (userAction.equals("2")) {
System.exit(0);
} else {
System.out.println("Sorry, your selection wasn't valid.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
This is all fine, and when the user types 1, pressPlay()
is called and it proceeds to the next method which does some stuff, mainly printing things to the screen. However, when I leave the pressPlay()
method and return back to this main method, I start getting errors for reading the Input:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at PlayGame.main(PlayGame.java:17)
Can you clue me in into how I can get around this? Much appreciated!
EDIT - I just want it to return to the while loop in the main method and ask for 1 or 2 again, and take a valid 1 or 2. My code goes all the way through to userAction = userInput.nextLine().trim();
without waiting for anymore user input the second time round, after leaving the pressPlay()
method.
EDIT - The pressPlay()
method produces a grid that the player is able to move around in by typing particular commands. It has a while (true) {
loop inside of it, as well as Scanner userInput = new Scanner(System.in);
which takes the players input. If the player types quit, it calls a break out of the while loop and returns back to the main method, where the problem then arises.
Upvotes: 2
Views: 3544
Reputation: 130
I've managed to fix the issue.
In both my main method and my pressPlay()
method, I was creating separate scanners taking input from System.in
, and this was causing problems as it would no longer take input from the main method. Instead I took the Scanner out of the main method and put it after public class PlayGame {
, and used this same scanner in both of my methods, rather than separate ones.
Thank you Jayamohan and Hossam for your input (:
Upvotes: 2