验证非负整数Java

时间:2017-09-20 04:28:08

标签: java validation exception integer try-catch

所以我试图对整数进行输入验证。我能够检查非整数字符和整数,但我不知道如何循环这两个条件。因此,例如,如果用户输入'然后' -1',然后' a'再次。这是我的进一步理解的代码。

while (true) {
    try {
        n = Integer.parseInt(reader.nextLine());
        break;
    } catch (NumberFormatException nfe) {
        System.out.print("Try again: ");
    }
}

while (n < 1) {

    System.out.print("Enter a number greater than on equal to 1: ");

    n = Integer.parseInt(reader.nextLine());
}

3 个答案:

答案 0 :(得分:0)

你需要为每个输入的测试检查两件事 - 如果他们输入“AAA”(例外),0(通过但是太小),“AAA”没有被你的第二个循环拾取。

while (true) {
    try {
        n = Integer.parseInt(reader.nextLine());
        if (n >= 1) break;
        // Only gets here if n < 0;
        System.out.print("Enter a number greater than on equal to 
    } catch (NumberFormatException nfe) {
        System.out.print("Try again: ");
    }
}

答案 1 :(得分:0)

用一个循环来做:

for (;;) { // forever loop
    try {
        n = Integer.parseInt(reader.nextLine());
        if (n > 0)
            break; // number is good
        System.out.print("Enter a number greater than on equal to 1: ");
    } catch (NumberFormatException nfe) {
        System.out.print("Try again: ");
    }
}

或者,如果您有许多验证规则:

for (;;) { // forever loop
    try {
        n = Integer.parseInt(reader.nextLine());
    } catch (NumberFormatException nfe) {
        System.out.print("Try again: ");
        continue;
    }
    if (n < 1) {
        System.out.print("Enter a number greater than on equal to 1: ");
        continue;
    }
    if (n > 20) {
        System.out.print("Enter a number less than on equal to 20: ");
        continue;
    }
    if (n % 3 == 0) {
        System.out.print("Enter a number that is not divisible by 3: ");
        continue;
    }
    break; // number is good
}

答案 2 :(得分:0)

您应该使用一个while循环来处理此问题或将其更改为do while循环

int n = 0;
do {
    try {
        n = Integer.parseInt(reader.nextLine());
    } catch (NumberFormatException nfe) {
        System.out.print("Try again: ");
    }
} while (n < 1);