Java: check if the following "field" exists in the array

Ive done this:

if( tal[i+1] ){
    if( tal[i] == tal[i+1]){
        match=true;
    }
}

But it does not seem to work.

I want to check if a field exists next to the current (i) in the tal [] array.

How can i fix this?

+3
source share
3 answers

If by "exists" you mean that "is not outside the boundaries", then you should check the length:

if (i+1 < tal.length) {
  // i+1 is a valid index in tal here
}
+12
source

You can check the length of an array with a field length, for example:

if (tal.length > i + 1) {
    // there is an elemnt at i + 1
}

As you did not say anything about your comparison line (the line containing ==), I think this is not part of the question.

Although I think you should put it in a for loop, for example:

for (int i=0; < tal.length - 1; i++) {
    // you can safely do something here involving tal[i] and tal[i + 1]
}
+1
source

well, all his code does, checks to see if the next element of the logical array is the same as the current element, after the first check that the next element is correct. I think he thinks he is doing something else, but without him he tells us that it is something rather difficult to do for change.

0
source

All Articles