Java: Check if next "field" in array exists
Ive made this:
if( tal[i+1] ){
if( tal[i] == tal[i+1]){
m开发者_C百科atch=true;
}
}
But it doesnt seem to work.
I want to check whether the field next to the current (i) exists, in the array tal[].
How can i fix this?
If by "exists" you mean "is not out of bounds", then you have to check the length:
if (i+1 < tal.length) {
// i+1 is a valid index in tal here
}
You can check the length of an array with the length
field, like:
if (tal.length > i + 1) {
// there is an elemnt at i + 1
}
As you did not mention anything about your comparison line (the line containing ==
) I think it is not part of the question.
Although I guess you should put it into a for loop like:
for (int i=0; < tal.length - 1; i++) {
// you can safely do something here involving tal[i] and tal[i + 1]
}
well, all his code does is check if the next element of the boolean array is the same as the current element after first checking if the next element is true. My guess is he thinks it does something else, but without him telling us what that something is it's rather hard to make recommendations for changes.
精彩评论