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;
}