public static int promptUser(Scanner in, String prompt, int min, int max) {
int userTempVal = 0;
do {
userTempVal = in.nextInt();
if (userTempVal < min || userTempVal > max) {
System.out.println(prompt);
}
}while (userTempVal < min || userTempVal > max);
return userTempVal;
}
This is my current code. I basically need to scan for the user's input and make sure that it's an integer between min and max. If it's not an integer between min and max, it displays the prompt and scans for a new int. My current code fails if the user inputs anything besides an int (so a double or a string). How can I get my code to display the prompt and continue the do while loop when the input is not an int? This is for a class i'm taking and the instructor hinted that we could use the hasNextInt() function to account for this, but every time I try to use it, it either doesn't work or I get an error. Please help, I'm a beginning programmer!
EDIT (Using has Next Int () parameter) :
public static int promptUser(Scanner in, String prompt, int min, int max) {
int userTempVal = 0;
do {
userTempVal = in.nextInt();
if (userTempVal < min || userTempVal > max || !in.hasNextInt()) {
System.out.println(prompt);
}
}while (userTempVal < min || userTempVal > max || !in.hasNextInt());
return userTempVal;
}
I get this error -> When I type an int, the program stops running. When I type a string:
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 MineTest.promptUser(MineTest.java:60)
at MineTest.main(MineTest.java:24)