Java:检查数组中的下一个“字段”是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5244231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:11:16  来源:igfitidea点击:

Java: Check if next "field" in array exists

javaarrays

提问by Karem

Ive made this:

我做了这个:

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

But it doesnt seem to work.

但它似乎不起作用。

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

我想检查数组 tal[] 中当前 (i) 旁边的字段是否存在。

How can i fix this?

我怎样才能解决这个问题?

回答by Joachim Sauer

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
}

回答by vbence

You can check the length of an array with the lengthfield, like:

您可以使用length字段检查数组的长度,例如:

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 循环中,比如:

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

回答by jwenting

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.

好吧,他的代码所做的就是在首先检查下一个元素是否为真之后检查布尔数组的下一个元素是否与当前元素相同。我的猜测是他认为它有其他作用,但如果他不告诉我们这是什么东西,就很难提出更改建议。