I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
Thanks for your time!
To use them as integers you will need to convert the user input into an integer using the int() function. e.g. age=int(input("What is your age?")) This line of code would work fine as long as the user enters an integer.
You take a String from user (a single line of numbers) and you split it by space, so you have all the numbers as String in the array. Then you have to parse them to int or do whatever you want with them. Save this answer.
To validate input in a while loop: Use a try/except or an if/else statement to validate the input. If the input is invalid, use a continue statement to continue to the next iteration. If the input is valid, use a break statement to break out of the loop.
Take the input using next
instead of nextInt
. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue.
Try this:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With