我在执行这个函数时遇到问题,如果数组中有两个连续的数字,它会打印出“true”,如果没有,则会打印出“false”。我得到的错误是 boolean 值无法转换为 int 并且在代码的最后一行中我必须在 System.out.println() 的括号内放入什么?
public class A1Q2 {
private static int hasTwoLengthRun(int[] array) {
for(int i=0; i < array.length; i++){
if(array[i+1] == array[i]){
return true;
}
else{
return false;
}
}
}
public static void main(String[] args) {
int[] array = new int[]{5, 16, 7, 35, -2, -9, 75};
System.out.println();
}
}
最佳答案
1)hasTwoLengthRun()
在返回 boolean
值时应返回 boolean
而不是 int
。
2) 它的逻辑有问题,因为只要数组的两个元素不相等,它就会返回 false
。
仅当您迭代了所有元素时,才应返回 false
。
3) 对于编译器来说,该方法不会返回值,因为您仅在 for
中返回值。如果您有一个没有元素的数组,则无需输入 for
并且不会返回任何内容。这是不合法的。
4) 当最后一次迭代使用数组外的索引时,您将得到一个带有 for
条件的 ArrayIndexOutOfBoundsException
。
这是一个应该可以工作的代码:
private static boolean hasTwoLengthRun(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
if (array[i + 1] == array[i]) {
return true;
}
}
return false;
}
关于java - 使用 boolean 表达式在数组列表中连续的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41784231/