Reputation: 57
Trying to get user input as an int between 0 and 100, and prompt the user to "try again" as long as their input does not match this criteria.
My code thus far is somewhat successful at accomplishing my goal:
import java.util.Scanner;
public class FinalTestGrade
{
public static void main(String[] args)
{
Scanner studentInput = new Scanner (System.in );
int testGrade;
System.out.println("Please enter your test grade (0 to 100)");
while (!studentInput.hasNextInt())
{
System.out.println("Your input does not match the criteria, please enter a number between 0 and 100");
studentInput.next();
}
testGrade = studentInput.nextInt();
while (testGrade > 100 || testGrade < 0)
{
System.out.println("Your input does not match the criteria, please enter a number between 0 and 100");
testGrade = studentInput.nextInt();
}
As you can see, the program will check that the input is an int. Once the user successfully enters an int, the program checks to make sure that their input is between 0 and 100. The problem arises when the user enters a non int in response to the second prompt (initiated by the second while loop). Below is an example:
run:
Please enter your test grade (0 to 100)
P
Your input does not match the criteria, please enter a number between 0 and 100
109
Your input does not match the criteria, please enter a number between 0 and 100
P
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at finaltestgrade.FinalTestGrade.main(FinalTestGrade.java:24)
Java Result: 1
BUILD SUCCESSFUL (total time: 9 seconds)
So long story short, I'm wondering if there's a way to combine my while loops so that input expressed as an int between 0 and 100 is accepted & saved as a variable. All input which doesn't meet this criteria should trigger a prompt which repeats until the input meets this criteria. Any suggestions?
Upvotes: 3
Views: 26497
Reputation: 10995
int testGrade = -1 ;
Scanner studentInput = new Scanner(System.in);
while (testGrade > 100 || testGrade < 0)
{
System.out.println("Your input does not match the criteria, please enter a number between 0 and 100");
while(!studentInput.hasNextInt())
{
studentInput.next() ;
}
testGrade = studentInput.nextInt();
}
Have an infinite loop to check if there are invalid characters in the stream. If so, consume it, that is what hasNextInt()
is for. If you enter something valid, that loop exits.
Upvotes: 1