【问题标题】:why wont this return false with the given array为什么给定数组不会返回false
【发布时间】:2020-12-31 14:49:13
【问题描述】:
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;
    }

【问题讨论】:

  • 第一个如果做return verify(array, ++index)
  • @azro 仅此一项是不够的。此更改将始终返回 false
  • 在 arzo 说的之后,在函数的开头添加一个基本情况的条件,如if(index &gt;= array.length/2) return true;
  • 你是不是想说array.length - (index - 1)
  • 添加你正在传递的索引

标签: java recursion return boolean-logic


【解决方案1】:

方法中最好不要打印结果,只打印返回值。

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

【讨论】:

    【解决方案2】:

    你可能想做这样的事情:

    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;
    }
    

    您需要确保子值传播到父值,并以不同的方式检查索引:这没有错,如果索引超过数组长度的一半,您只是不想检查值这样的索引。

    【讨论】:

    • 看起来else里面除了print其实什么都没有
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 2013-09-18
    • 2011-11-30
    • 2022-08-14
    相关资源
    最近更新 更多