Mnai
Mnai

Reputation: 507

For loop logic runs but doesn't make sense

VisitProcedure.length equals 7

So for some reason this method works how I want it to. But the logic makes no sense to me. I have an array of 7 and i want the user to type in some part of the index 0-6 and it will display the value at that index. If they type in a number thats out of bounds then it throws an exception. But this is how i read the if statement logic

if index is less then 0 or index is greater then 6 do this (p = VisitProcedure[index].getProcedure(); //displays the index

But instead it does the opposite. When i pick 0-6 It displays the value of the array at that index. And when i do anything else its out of index. Also when i try a different logic

if index is greater then equal to 0 and less then 7 do this

I still run into error. But basically everything works fine it just doesnt make sense to me why.

public Procedure GetByIndex(int index)throws ArrayIndexOutOfBoundsException {
            Procedure p;
            if (index < 0 || index > 1 - VisitProcedure.length) { //switching 1 - to - 1 still doesnt work
                p = VisitProcedure[index].getProcedure();
                return p;   
            }
            else{
                ArrayIndexOutOfBoundsException ar;
                ar = new ArrayIndexOutOfBoundsException(); 
                throw ar;
                //throw new ArrayIndexOutOfBoundsException();

            }
        }

Upvotes: 1

Views: 78

Answers (2)

Eran
Eran

Reputation: 393781

Your current code is wrong, but it works anyway for the following reasons:

  • if you pass a valid index (between 0 and 6), index > 1 - VisitProcedure.length is true (since 1 - VisitProcedure.length is negative), so the if condition is true and you return VisitProcedure[index].getProcedure().

  • If you pass an invalid index > 6 or index < 0, the condition is still true, and accessing an invalid index of the array throws ArrayIndexOutOfBoundsException (i.e. it is still thrown, but not by the else clause).

In other words, your condition is always true, so your code is equivalent to:

public Procedure GetByIndex(int index)throws ArrayIndexOutOfBoundsException {
    return VisitProcedure[index].getProcedure();
}

Upvotes: 1

Abdul Rahman Shamair
Abdul Rahman Shamair

Reputation: 578

If(index>0 && index<=VisitProcedure.length-1){
    //if index is greater than 0 and less than or equal to index 6

    p = VisitProcedure[index].getProcedure();
            return p; 

}else{
 ArrayIndexOutOfBoundsException ar;
            ar = new ArrayIndexOutOfBoundsException(); 
            throw ar;
            //throw new ArrayIndexOutOfBoundsException();

}  

Upvotes: 0

Related Questions