Keep asking until the input is valid
20 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Users make typing mistakes, like abc for their age. Instead of crashing, a program can catch the exception, show a short message and ask again until the input is valid.
Bad input stays in the Scanner
A loop asks for an age, the user types abc, and the error message then prints forever. When nextInt() fails, the Scanner keeps the bad text, so the next nextInt() reads the same abc and fails again.
try { age = sc.nextInt();} catch (InputMismatchException e) { sc.nextLine(); // throw away the bad text, like "abc" System.out.println("Please type a number.");}sc.nextLine() in the catch block reads the rest of the bad line and throws it away, so the next read waits for new input. It is the same leftover-text idea as in The leftover Enter (opens in a new tab).
Loop until the input is valid
The program should ask again, as many times as needed. Put the question and the try-catch inside while (true), and leave with break once a value is good, as in break and continue (opens in a new tab).
Example 1 · Ask again with nextInt()
import java.util.InputMismatchException;import java.util.Scanner;
public class AskAge { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (true) { System.out.print("Enter your age: "); try { int age = sc.nextInt(); System.out.println("Next year you will be " + (age + 1)); break; } catch (InputMismatchException e) { System.out.println("Please type a whole number"); sc.nextLine(); } } }}Enter your age: abc Please type a whole number Enter your age: 12.5 Please type a whole number Enter your age: 19 Next year you will be 20
What this code does
abcand12.5are not whole numbers, sonextInt()throws and the catch block runs;sc.nextLine()then throws the bad line away.- Nothing after the catch block ends the loop, so
while (true)asks again. 19works: the age is used, andbreakleaves the loop.
Read a line, then convert
Another way leaves no bad text behind: read the whole line with sc.nextLine() and convert it with Integer.parseInt(line.trim()). Bad text then throws NumberFormatException instead.
Example 2 · nextLine() and parseInt
import java.util.Scanner;
public class AskMarks { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (true) { System.out.print("Enter marks: "); String line = sc.nextLine(); try { int marks = Integer.parseInt(line.trim()); System.out.println("Saved: " + marks); break; } catch (NumberFormatException e) { System.out.println("Not a number: " + line); } } }}Enter marks: eighty Not a number: eighty Enter marks: 82 Saved: 82
What this code does
- Every round reads one full line, so no bad text is left in the Scanner and no
sc.nextLine()is needed in catch. - The user typed a space before 82;
trim()removes it, soparseIntworks.
Not a number, or out of range?
A user types 5000 at an ATM whose limit is 2000. That is a real number, so no exception comes: check the range with if, and keep catch for text that is not a number.
Example 3 · Number check and range check together
import java.util.Scanner;
public class AtmAmount { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (true) { System.out.print("Amount (1-2000): "); String line = sc.nextLine(); try { int amount = Integer.parseInt(line.trim()); if (amount >= 1 && amount <= 2000) { System.out.println("Take your cash: " + amount); break; } System.out.println("Enter 1 to 2000, not " + amount); } catch (NumberFormatException e) { System.out.println("Digits only: " + line); } } }}Amount (1-2000): 5000 Enter 1 to 2000, not 5000 Amount (1-2000): abc Digits only: abc Amount (1-2000): 1500 Take your cash: 1500
What this code does
5000converts fine but fails theif, so the range message prints and the loop asks again.abcnever reaches theif:parseIntthrows, and the catch block answers.- Only a value that passes both checks reaches
break.
Classify
Catch it or check it?
Tap what the user typed, then tap how the program should deal with it.
Next step
Check your understanding
8 quick questions