How to prevent program termination when the user enters a string when the program expects an integer?

I am trying to set up a do-while loop that will repeatedly ask the user for input until it enters an integer greater than zero. I cannot use try-catch for this; it is simply not allowed. Here is what I have:

Scanner scnr = new Scanner(System.in);
int num;
do{
System.out.println("Enter a number (int): ");
num = scnr.nextInt();
} while(num<0 || !scnr.hasNextLine());

It will loop if a negative number is entered, but if there is a letter, the program ends.

+3
source share
2 answers

, , . , num , . , num -1, , , while , .

Scanner scnr = new Scanner(System.in);
int num = -1;
String s;
do {
    System.out.println("Enter a number (int): ");
    s = scnr.next().trim(); // trim so that numbers with whitespace are valid

    if (s.matches("\\d+")) { // if the string contains only numbers 0-9
        num = Integer.parseInt(s);
    }
} while(num < 0 || !scnr.hasNextLine());

:

Enter a number (int): 
-5
Enter a number (int): 
fdshgdf
Enter a number (int): 
5.5
Enter a number (int): 
5
+5

try-catch , nextLine()
nextInt(), , String - .

import java.util.Scanner;

public class Test038 {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        int num = -1;
        do {
            System.out.println("Enter a number (int): ");
            String str = scnr.nextLine().trim();
            if (str.matches("\\d+")) {
                num = Integer.parseInt(str);
                break;
            }

        } while (num < 0 || !scnr.hasNextLine());
        System.out.println("You entered: " + num);
    }

}
+3

All Articles