billabrian6 billabrian6 - 1 year ago 78
Java Question

How to limit the user to only input an integer?

First, I would like to say that this is for a homework assignment and I'm only looking for suggestions. Not answers! I am very determined to learn and be good at programming, and that doesn't come from someone else doing your work. Point me in the correct direction and it will be greatly appreciated!

Please know that I have searched the internet for a solution but haven't found one that fits my needs. I'm unable to use any advanced methods.

The program is to allow the user to input a start and end number for a range. The start number must be divisible by ten and the end must be divisible by ten and not be the same as the starting number. The user is limited to use only numbers between 0 - 1000 and not be allowed to enter any other characters on the keyboard. So if they hit "a" or "1200" the program should loop back until a valid entry has been entered.

Currently I'm stuck on only allowing an integer to be input. The particular part of my code is posted below:

while(errorLoop != true){
System.out.println("Enter the Starting Number of the Range (ex. 10,70,100)");
startNum = kb.nextInt();
System.out.println("Enter the Ending Number of the Range (ex. 10,70,100)");
endNum = kb.nextInt();
if(startNum % 10 == 0 && endNum % 10 == 0){
errorLoop = true;
errorLoop = false;
System.out.println("Start and End of range must be divisible by 10\n");
System.out.println("Please try again (ex. 10,70,100)\n");

I have only posted the part of the code that pertains to the question. If you must know the point of the program, the range of numbers will be sorted by prime numbers and output to a table looking format where each row ends with a number that is divisible by ten. The non-prime numbers will be printed as a "-".

71 - 73 - - - - - 79 | 80 \n and it goes on for however big the range is.

Answer Source

I would advise you to use nextLine() instead of nextInt(). Then you can first make sure that it is parseable as an Integer (check the Integer JavaDoc page), and then that the number meets your requirements.

To handle the case where the input isn't numeric, you can go in several directions. I prefer checking the input before the actual parse call with a regex. A String containing only digits would match "^\\d+$" (check out this link for a great regex tutorial), and there is a handy method in the String API.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download