Lanhua
Lanhua

Reputation: 13

Why index greater than for loop condition leads to exception [Java]?

I am searching for matching elements in two arrays. If the matching element was found I set k and j greater than the for loop conditions to quit the cycle, but I get an exception at inner loop condition. Granted, I can fix it by using break outerloop;, but isn't setting index greater than the for loop condition supposed to exit the loop?

//outerloop:
for (int j = 0; j < listOfSubcategories.size(); j++) {
    if (listOfSubcategories.get(j).subcatName.equals(rawOptions.get(i).subcatName)) { //if the subcatName exists 

        for (int k = 0; k < listOfSubcategories.get(j).listOfID.size(); k++) {

            if (0 == rawOptions.get(i).codeID.compareTo(listOfSubcategories.get(j).listOfID.get(k).codeID)) {//if this id (as in 0090-01 exists
                    listOfSubcategories.get(j).listOfID.get(k).usageCount += rawOptions.get(i).usageCount;
                    isProcessed = true;
                    k=listOfSubcategories.get(j).listOfID.size();  //this fails
                    j = listOfSubcategories.size();
                    //break outerloop;                      //this works
                }

             } 
         }
    }

Upvotes: 0

Views: 77

Answers (1)

sixtytrees
sixtytrees

Reputation: 1233

First of all, can you please post your stack trace?

Second, your exception is most likely caused by j = listOfSubcategories.size(); This makes comparison k < listOfSubcategories.get(j).listOfID.size() impossible.

The code below works.

public class ForArray {

    public static void main(String[] args) {


        int[] myIntArray = {1, 2, 3};  //This is my Array
        int searchingForThisNumberInArray = 2; //Search for this number in an array
        int index=-1; //Index of the first matching element. -1 if element not found.

        for (int i = 0; i < myIntArray.length; i++) { //Check each element
            if (myIntArray[i] == searchingForThisNumberInArray) { //if this element contains correct number
                index = i; //Save it in index
                i = myIntArray.length; //Quit for cycle by increasing i.
            }
        }
        System.out.println(index);
    }    
}

Upvotes: 1

Related Questions