Skip to content
Advertisement

JAVA Method returns unexpected value

I am a very new java programmer, the below code is my first attempt at my own project. I’m certain the code is a mess, please forgive me.

In the below code the user is prompted to enter 5 values between 1 and 50. I am placing the input values into an int[]. I want to verify that the numbers are in range so I pass the value to a method. MY ISSUE: If the value is in range it gets returned then the for loop increments to repeat – Good Behavior If an invalid value is entered the check is done, error message is displayed and the user is prompted to reenter a proper value. If one invalid entry is made and a proper value is entered on the second attempt, a correct value is returned – Good Behavior If two invalid entries are made the second invalid entry somehow gets passed back to the for loop and gets added to array – BAD Behavior

I am certain there is something simple I am missing.

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("you get 5 elements between 01 & 50:");
    int a[] = new int[5];
    System.out.println("nEnter all the elements:");
    for(int i = 0; i < 5;)
    {
        int b = in.nextInt();
        a[i] = checkNum(b);
        i++;
    }
    System.out.println("Numbers:" + Arrays.toString(a));
    in.close();
}

static int checkNum(int z) {
    Scanner s = new Scanner(System.in);
    if (z>0 && z<51) {
        return z;
    } else {
        System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
        int qz = s.nextInt();
        z = qz;
        checkNum(qz);
    }
    return z;
}

Advertisement

Answer

The problem resides in your checkNum(), you are using recursion here, I don’t think you know this (if you do that’s great).

You need to return the checkNum(qz) value, I have simplified your logic a bit.

static int checkNum(int z) {
    if (z<1 || z>50) // check for false value 
    {
        System.out.println("Invalid Entry!! Enter a valid number between 01 & 50");
        Scanner s = new Scanner(System.in);
        return checkNum(s.nextInt());
    }
    return z;
}
Advertisement