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.

有帮助吗?

解决方案

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

其他提示

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

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top