Skip to content
Advertisement

Finding 4 consecutive same value integers in an unsorted array – Java

I’ve looked all around but could not find someone who has done this in java for some reason. I need to make a section of code that takes an array of single spaced integers and determines whether or not there are four consecutive, same value, integers in it. (I’ve coded in other languages before but I am trying to learn Java so the fact that I cannot get this to work drives me insane.) I’ve included below what code I’ve written so far.

public static boolean isConsecutiveFour(int[] checkArray) {  

    for (int i = 1; i < checkArray[0]-1; i++){
        int lower2 = [checkArray[i-2] intValue];
        int lower1 = [checkArray[i-1] intValue];
        int mid = [checkArray[i] intValue];
        int upper1 = [checkArray[i+1] intValue];
        int upper2 = [checkArray[i+2] intValue];

        if ((lower2 == lower1 && lower1 == mid && mid == upper1) 
                                    || 
            (lower1 == mid && mid == upper1 && upper1 == upper2)) {
            return true;
        }
    } 
    return false;
}

Advertisement

Answer

What went wrong in your code?

The other answer shows you a quick and smart way to obtain your result directly from the user input. I’ll take a look at your code and fix the bugs.

You’ve got a syntax problem here:

        int lower2 = [checkArray[i-2] intValue];

The outer square brackets and the word intValue don’t belong here. Assuming that you have already put the user input into an array of integers (as the parameter declaration int[] checkArray says), you may just do:

        int lower2 = checkArray[i - 2];

Similar for the other assignments.

Next you have got some boundary condition problems. The first time through your loop i is 1, so checkArray[i-2] tries to take out an element at index -1. Array indices go from 0 and up, so this throws an exception. Instead start your loop from int i = 2. Indices goes up to one less than the array length. You get the array length from checkArray.length. Since you want to do checkArray[i+2], you need that i < checkArray.length - 2, so let this be your condition in the for loop.

No, wait. Your third problem is not an error, just an over-complication of the logic: You are taking out five consecutive integers into lower2, lower1, mid, upper1 and upper2. You needed only four. So not to make things more complicated than needed delete upper2. Now you only need checkArray[i + 1], so you can and must allow i < checkArray.length - 1. Now you only need the first half of the if condition, which makes the if statement a lot easier to read and understand.

That’s it.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement