我需要检查数组中是否包含 1,然后数组中是否包含 2。
我编写的代码仅检查两者是否都在那里,而不是检查其中一个是否在另一个之前。我怎样才能做到这一点?
if(array[i] == 1)
count++;
else if(array[i] == 2)
count++;
}
if(count > 1)
System.out.print("true");
else
System.out.print("false");
比较值的索引有效!
if (nums[i] == 1)
value1 = i;
else if(nums[i] == 2)
value2 = i;
}
if (value2 > value1)
System.out.print("true");
else
System.out.print("false");
最佳答案
这应该可以!
public void hasOneThenTwo(int[] a) {
bool hasOne = false;
for (int i = 0; i < a.length; ++i) {
if (!hasOne && a[i] == 1) {
hasOne = true;
} else if (hasOne && a[i] == 2) {
return true;
}
}
return false;
}
关于java - 检查数组是否在另一个 int 之前包含某个 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30315535/