Java 对于给定的数组,为什么不返回false int[]array2=新的int[]{1,2,6,6,3,1,}; //方法检查在反转数组时给定的数组内容是否保持不变 公共静态布尔验证(int[]数组,int索引){//方法接受数组和索引号 if((数组[index]==数组[array.length-index-1])&&(索引
您可能希望执行以下操作:Java 对于给定的数组,为什么不返回false int[]array2=新的int[]{1,2,6,6,3,1,}; //方法检查在反转数组时给定的数组内容是否保持不变 公共静态布尔验证(int[]数组,int索引){//方法接受数组和索引号 if((数组[index]==数组[array.length-index-1])&&(索引,java,recursion,return,boolean-logic,Java,Recursion,Return,Boolean Logic,您可能希望执行以下操作: 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[ind
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;
}
公共静态布尔验证(int[]数组,int索引){
if(数组[索引]==数组[数组.长度-索引-1]){
if(索引<数组长度/2)
返回验证(数组+索引);
返回true;
}否则{…}
返回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;
}
印刷品
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));
首先,如果do
返回verify(数组,++索引)
@azro,仅此一项是不够的。这个更改总是返回false
同样在函数的开头,您是否想说array.length-(index-1)
?添加您要传递的索引除了打印之外,似乎没有其他内容
true
true
false
true
true
false