我有一个名为 e 的数组,该数组包含对象,但并非在每个索引上。因此,我使用 for 循环来查找数组中包含对象的第一个索引。我通过查找不为空的值来做到这一点。如果找到它,我会将索引保存在名为 index 的变量中并跳出循环。如果找不到不包含空值的索引,我想从该方法返回。否则,我想继续并使用包含数组索引的变量索引。
int index;
for (int i = 0; i < e.length; i++) {
if (e[i] != null) {
index = i;
break;
}
}
// if index did not get any value inside the for-loop, return
// And here I use the index that was found using the for-loop
如何检查变量索引是否从 for 循环中获得了新索引?
谢谢!
最佳答案
这是始终初始化变量的原因之一。如果初始化,您可以使用该值执行操作(并避免不必要的 boolean 标志)
int index = -1;
for (int i = 0; i < e.length; i++) {
if (e[i] != null) {
index = i;
break;
}
}
if (index == -1) return;
关于java - 查找数组中不存在空值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16195453/