Java code to make sure a user enters correct input to a program

How can I make sure that a user only enters a positive integer value of 1, 2, or 3 and keep prompting for another input if they enter a word, symbol, or negative number?  Attached is my current code.  Right now, my results are:

1. Monitor an Animal
2. Monitor a Habitat
3. Quit
Please choose an option:  apple
Please enter a valid option: horse
Please enter a valid option: 12422
Please enter a valid option: &
Exception in thread "main" java.util.InputMismatchException
      at java.util.Scanner.throwFor(Scanner.java:864)
      at java.util.Scanner.next(Scanner.java:1485)
      at java.util.Scanner.nextInt(Scanner.java:2117)
      at java.util.Scanner.nextInt(Scanner.java:2076)
attempt.txt
LVL 1
NAMEWITHELD12Asked:
Who is Participating?
 
CEHJCommented:
The instructor is wrong ;) I would penalize for mixing CLI and GUI. Since he plans to reward you for doing exactly that then you need to satisfy the requirements

Just loop until the prompt returns a correct value. Actually the use of next() would be easier than nextInt()
0
 
CEHJCommented:
If you're using JOptionPane ( i know you are ;) ) then it's best to stick with that and not mix it with command line entry. Use JOptionPane.showInputDialog and do it in a loop until acceptable input is submitted
0
 
ste5anSenior DeveloperCommented:
@CEHJ: How?? It looks like a simple console application..
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
NAMEWITHELD12Author Commented:
:) @ CEHJ.  That part was only for a popup later in the program if a bunch of asterisks are located in the file the program is reading.  I'm not allowed to use any dialog boxes for the rest of the program.  The program is basically all CLI.
0
 
CEHJCommented:
OK - then why not get rid of ALL dialog boxes? You shouldn't mix CLI and GUI
0
 
NAMEWITHELD12Author Commented:
The pop-up is in a totally different method, and the instructor specifically says "If it doesn't generate a pop-up if ***S are found, you will get a B instead of an A".  I just need to know how to fix the very *first* menu so that the user can only enter 1, 2, or 3.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.