简体   繁体   中英

Validating Non Negative Integer Java

So I am trying to do input validation for an integer. I am able to check non integer characters and also for integers but I am not sure how to loop both of these conditions. So for example if the user enters 'a', then '-1', and then 'a' again. Here is my code for further understanding.

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

You need to check both things for every test entered - what if they type "AAA" (exception), 0 (passes but is too small) "AAA" not picked up by your second loop.

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

Do it with one loop:

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

Or, if you have many validation rules:

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
}

You should use one while loop to handle this or change it to a do while loop

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM