Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent program from terminating when user inputs a string when the program expects an integer?

I'm trying to set up a do-while loop that will re-prompt the user for input until they enter an integer greater than zero. I cannot use try-catch for this; it's just not allowed. Here's what I've got:

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'll loop if a negative number is inputted, but if a letter is, the program terminates.

like image 243
user3315240 Avatar asked Dec 12 '25 03:12

user3315240


2 Answers

You can take it in as a string, and then use regex to test if the string contains only numbers. So, only assign num the integer value of the string if it is in fact an integer number. That means you need to initialize num to -1 so that if it is not an integer, the while condition will be true and it will start over.

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());

Sample run:

Enter a number (int): 
-5
Enter a number (int): 
fdshgdf
Enter a number (int): 
5.5
Enter a number (int): 
5
like image 173
Michael Yaworski Avatar answered Dec 13 '25 17:12

Michael Yaworski


As using try-catch is not allowed, call nextLine() instead
of nextInt(), and then test yourself if the String you got
back is an integer or not.

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);
    }

}
like image 39
peter.petrov Avatar answered Dec 13 '25 16:12

peter.petrov