为什么这个 return false 对于给定的数组
why wont this return false with the given array
int[] array2 = new int[]{1,2,6,6,3,1,};
//method checks if the given array contents remain the same when array is reversed
public static boolean verify(int[] array, int index) {//method takes array and an index number
if ((array[index] == array[array.length - index-1]) && (index < array.length/2)) {
System.out.print("true/");
verify(array, ++index);// increase index number to check the next values in the th array
return true;
} else
System.out.println("..false..");
return false;
}
您可能想做这样的事情:
public static boolean verify(int[] array, int index) {
if (array[index] == array[array.length - index-1]) {
if(index < array.length/2)
return verify(array, ++index);
return true;
} else {...}
return false;
}
您需要确保子值传播到父值,并以不同方式检查索引:没有错,如果索引超过数组长度的一半,您只是不想检查此类索引的值。
最好不要在方法中打印结果,而只打印 return 值。
public static boolean verify(int[] array, int index) {
// don't go passed the middle
if (index >= array.length/2) {
return true;
}
// return as soon as a false comparison is found
if(array[index] != array[array.length-index-1]) {
return false;
}
// Try the next value
return verify(array, index + 1);
}
System.out.println(verify(new int[] {1,2,3,3,3,2,1}, 0));
System.out.println(verify(new int[] {1,2,3,3,2,1}, 0));
System.out.println(verify(new int[] {1,2,4,3,3,2,1}, 0));
System.out.println(verify(new int[] {1,2,4,3,3,4,2,1}, 0));
System.out.println(verify(new int[] {1}, 0));
System.out.println(verify(new int[] {1,2}, 0));
版画
true
true
false
true
true
false
int[] array2 = new int[]{1,2,6,6,3,1,};
//method checks if the given array contents remain the same when array is reversed
public static boolean verify(int[] array, int index) {//method takes array and an index number
if ((array[index] == array[array.length - index-1]) && (index < array.length/2)) {
System.out.print("true/");
verify(array, ++index);// increase index number to check the next values in the th array
return true;
} else
System.out.println("..false..");
return false;
}
您可能想做这样的事情:
public static boolean verify(int[] array, int index) {
if (array[index] == array[array.length - index-1]) {
if(index < array.length/2)
return verify(array, ++index);
return true;
} else {...}
return false;
}
您需要确保子值传播到父值,并以不同方式检查索引:没有错,如果索引超过数组长度的一半,您只是不想检查此类索引的值。
最好不要在方法中打印结果,而只打印 return 值。
public static boolean verify(int[] array, int index) {
// don't go passed the middle
if (index >= array.length/2) {
return true;
}
// return as soon as a false comparison is found
if(array[index] != array[array.length-index-1]) {
return false;
}
// Try the next value
return verify(array, index + 1);
}
System.out.println(verify(new int[] {1,2,3,3,3,2,1}, 0));
System.out.println(verify(new int[] {1,2,3,3,2,1}, 0));
System.out.println(verify(new int[] {1,2,4,3,3,2,1}, 0));
System.out.println(verify(new int[] {1,2,4,3,3,4,2,1}, 0));
System.out.println(verify(new int[] {1}, 0));
System.out.println(verify(new int[] {1,2}, 0));
版画
true
true
false
true
true
false