Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
Thread: Help with simple Java problem?
10-21-2011, 09:01 PM #1
- Join Date
- Oct 2011
- Thanked 0 Times in 0 Posts
Help with simple Java problem?
My technology teacher would like me to create a basic text game as a way to demonstrate user input.
Here's the problem:
I am using a Scanner to get user input and set that input to a varible:
System.out.println("If you're ready, type any number to begin:");
That sets A1 to whatever the user types in. If the user were to type in a number that's not a choice, nothing happens. If the user types in anything but a number, they get an error.
What do I use to repeat the question if they type in something that is not an option?
10-21-2011, 10:46 PM #2
- Join Date
- Sep 2002
- Saskatoon, Saskatchewan
- Thanked 2,660 Times in 2,629 Posts
You capture the results as a string with nextLine instead, try/catch a cast to number with an Integer.parseInt, and then compare it to what is valid. Alternatively, you can use the Scanner's hasNext* methods to determine if the next token matches the proper type, and flush it when its invalid. That saves the try/catch with the cast.