I want the user to input integers between 80 and 120 with no alphabets and other symbols. Here are my codes:
import java.util.*;
public class Test {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
//checking for integer input
while (!in.hasNextInt())
{
System.out.println("Please enter integers between 80 and 120.");
in.nextInt();
int userInput = in.nextInt();
//checking if it's within desired range
while (userInput<80 || userInput>120)
{
System.out.println("Please enter integers between 80 and 120.");
in.nextInt();
}
}
}
}
However, I'm facing an error. Is there a solution to this?
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Array.main(Array.java:15)
Thank you! :)
EDIT: Thank you Tom, got the solution, but would like to try without "do"
Scanner in = new Scanner(System.in);
int userInput;
do {
System.out.println("Please enter integers between 80 and 120.");
while (!in.hasNextInt())
{
System.out.println("That's not an integer!");
in.next();
}
userInput = in.nextInt();
} while (userInput<81 || userInput >121);
System.out.println("Thank you, you have entered: " + userInput);
}
}