Universal procedure:
- Read the input in an infinite loop.
- Use
break; to exit the loop when conditions are met.
Example:
Scanner keyboard = new Scanner(System.in); int startr, endr; for (;;) { System.out.println("Enter the starting number of the range: "); startr = keyboard.nextInt(); if (startr >= 0 && startr % 10 == 0) break; System.out.println("Number must be >= 0 and divisible by 10."); } for (;;) { System.out.println("Enter the ending number of the range: "); endr = keyboard.nextInt(); if (endr <= 1000 && endr % 10 == 0) break; System.out.println("Number must be <= 1000 and divisible by 10."); }
If, after an invalid input, you only want to display an error message without repeating the initial prompt, move the initial prompt directly above / outside the loop.
If you do not need a separate error message, you can re-arrange the code to use the do-while loop to check for conditions that are slightly shorter:
Scanner keyboard = new Scanner(System.in); int startr, endr; do { System.out.println("Enter the starting number of the range."); System.out.println("Number must be >= 0 and divisible by 10: "); startr = keyboard.nextInt(); } while (!(startr >= 0 && startr % 10 == 0)); do { System.out.println("Enter the ending number of the range."); System.out.println("Number must be <= 1000 and divisible by 10: "); endr = keyboard.nextInt(); } while (!(endr <= 1000 && endr % 10 == 0));
source share