O Fakos O Fakos - 7 months ago 16
Java Question

How do I simplify this integer validation?

I'm new to Java, and I'm working on a method in my program that checks the users input to be within bounds, not a null value (zero), not a letter, and a positive number. So originally I incorporated two while loops within this method to check for the validity of these inputs, but I would like to simplify it in one loop. I'm getting an error when I input a letter (ex. a) after a few inputs, and I believe it is due to the two different while loops making it more complicated. Can someone help me with this please?

public static void valid(String s, int max)
{
while(sc.hasNextInt() == false) {
System.out.println("That is not correct. Try again:");
sc.nextLine();

}

int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
sc.nextLine();
return;

}

Answer

You have:

int value;
    while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
        System.out.println("That is not correct. Try again: ");
        sc.nextLine();
    }

Which is doing sc.nextInt() twice, so value does not necessarily have the same value in these two cases and it is also asking you for a number twice.

A fix would be something like this:

int value;
    while((value = sc.nextInt()) > max || value <= 0) {
        System.out.println("That is not correct. Try again: ");
        sc.nextLine();
    }

which would make it better but you still have issues. If value is bigger than max, then the loop will iterate again calling nextInt() but this time you have not checked for hasNextInt(). This is why you'd better have everything in one loop. Something like this:

public static void valid(String s, int max) { 
    while(true) {
        if(!sc.hasNextInt()) { //this is the same as sc.hasNextInt() == false
            System.out.println("That is not correct. Try again:");
            sc.nextLine();
            continue; //restart the loop again
        } else {
            int value = sc.nextInt();
            if(value > max || value <= 0) {
                System.out.println("That is not correct. Try again:");
                sc.nextLine();
                continue; //restart the loop from the top - important!
            } else {
                extendedValidation(value, s);
                return;
            }
        }
    }
}