1

I'm almost new at Java! I want to control if there are 4 consecutive elements in an array with 5 elements. Is there any way to do that? Can someone help me with that? Thanks! Consecutive like {2, 3, 4, 5}. If there is {3, 4, 2, 5} for example this is not consecutive.I want just a simple example if someone can help me.

I did this but I think this is incorrect:

 public int katerTeNjepasnjeshme()
 {
         int[] numrat=new int[zar.length];
         for(int i=0;i<zar.length;i++)
             numrat[i]=zar[i].getValue();
         int shuma=0;
         for(int i=0;i<zar.length-1;i++)
         {


    if(zar[i+1].getValue()==(zar[i].getValue()+1))
         Joptionpane.showMessageDialog(null,"Tere are cons elements");
}
1
  • constructiveness is calculated by formula a[i+1] = a[i] +1 Commented Jan 28, 2016 at 19:30

3 Answers 3

1

Here's the general idea:
Keep a counter (initialized appropriately), to keep track of the number of consecutive elements as you iterate over the elements.
If the counter reaches 4, you have found 4 consecutive elements.
If you encounter an element that is not consecutive, then reset the counter to 1, and proceed to check the next element.

Here is a sample code snippet:

public static void findConsecutive()
    {
        int[] array = {1,2,3,5,6,7,8,10};

        int counter = 1;
        int i = 1;
        for (i = 1; i < array.length; i++)
        {
            if (array[i] == (array[i-1] + 1))
            {
                counter++;
                if (counter == 4)
                {
                    System.out.println("Consecutive elements are at array index: " + (i - 3) + " to " + i);
                    break;
                }
            }
            else
            {
                counter = 1;
            }
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

@Doen - Added a sample code to explain the steps listed.
1

i think something like that should work:

int[] mylist = new int[10];

for (int i = 0; i < myList.length; i++) {
    int k = 1;
    for (int j = 1; j < 5 j++) {
        if (mylist[i] == mylist[i+j]-j) {
            k++;
        }
        if (k=5) System.out.println("found");
    }
}

Comments

0

As soon as you need to compare two elements of the array you should use proper bounds in the loop, otherwise you will get ArrayIndexOutOfBoundsException

boolean consequtive = true;
for (int i = 0; i < zar.length - 1; i++)                                 
    if (zar[i+1].getValue() != zar[i].getValue() + 1) {
        consecutive = false;
        break;
    }    
if (consequtive)
    Joptionpane.showMessageDialog(null,"Tere are cons elements");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.