1

I have a method that's supposed to go through an array and check if there's any multiples and if there is, it returns 'true' and if there is not, it returns 'false'. My issue lies in my for loop where I keep getting an error:

ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5

I believe it works if there is an occurrence but if there is not I get the error.

This is my method now:

public static boolean hasAHit (int[] theCounts){
        //for loop scans the elements of theCounts
        //when it finds a value greater than or equal to 2, = true
        boolean ifTrue = false;
        for (int i = 0; i < theCounts[i]; i++){
            if (theCounts[i] >= 2){
                ifTrue = true;
            }
            else {
                ifTrue = false;
            }
        }
        return ifTrue;
    }

and this is how I thought I'd be able to fix it by using the array's length instead, but It now would give me 'true' if the array's length is greater than two rather than if there's two or more occurrences IN the array:

public static boolean hasAHit (int[] theCounts){
        //for loop scans the elements of theCounts
        //when it finds a value greater than or equal to 2, = true
        boolean ifTrue = false;
        for (int i = 0; i < theCounts.length - 1; i++){
            if (theCounts[i] >= 2){
                ifTrue = true;
            }
            else {
                ifTrue = false;
            }
        }
        return ifTrue;
    }
Paige
  • 159
  • 6
  • Hi, when you find a value greater than 2 shouldn't you immediately return true? – dreamcrash Apr 05 '21 at 15:33
  • `public static boolean hasAHit (int[] theCounts) { for (int i = 0; i < theCounts-1; i++) { for (int j = i+1; j < theCounts; j++) { if (theCounts[i]==theCounts[j]) return true; } } return false; }` – Jörg Apr 05 '21 at 15:39
  • Thank you @Jörg I completely forgot I could just compare two values going through the array, but why is the first loop's length -1 while the second loop doesn't need it? – Paige Apr 05 '21 at 16:55
  • Because the inner loop starts with i+1. Thus you compare each element of the outer loop to its adjacent next element of the array. Without -1 variable j of the inner loop would point beyond the limits of the array when doing the last run of the outer loop; and hence the ArrayIndexOutOfBoundsException. – Jörg Apr 07 '21 at 04:56

0 Answers0