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)
hasNextInt()istrueis the correct strategy to ensure that a subsequent call tonextInt()will successfully return anint. It can be made to work. Can you show us how you tried to use it?hasNextInt()before callingnextInt(). Whole point of this method is to determine if it is safe to get data as int. If its result isfalsesimply consume that invalid token using other methods which can accept any type of data likenext()ornextLine()and ask for another value.