【问题标题】:Smallest Length array最小长度数组
【发布时间】:2016-06-16 19:59:52
【问题描述】:

所以我想创建一个方法,从两个给定的数组中输出一个长度最小的数组,但该方法总是要求在 if 语句之外返回

public static int[][] SmallestArray(int[][] A, int[][] B){
    if(A.length < B.length){
        if(A[0].length <B[0].length)
            return A;
    }
    else if(B.length < A.length){
        if(B[0].length <A[0].length)
            return B;
    }
}

【问题讨论】:

  • 你忘记了 B.length == A.length 大小写
  • 你没有覆盖所有的执行路径。所有非 void 方法都需要返回语句的路径
  • 那是因为仍然存在不满足任何条件的情况。然后你会进入一个未被覆盖的分支,但该方法仍然需要返回一些东西。例如:AB 长度相同时会发生什么?
  • 比如A[0] &gt; B[0]在第一个条件下呢?另外,你不能保证得到一个方形数组,所以A[1] 可能比A[0]
  • 有人告诉我 A[0].length 返回数组中列的 nr

标签: java arrays methods


【解决方案1】:

您的代码中有未发现的路径。这意味着在某些情况下,您的方法的执行在没有遇到return 语句的情况下完成。但是既然你声明了你的方法返回了int[][],那它就必须返回到某个地方。

以下是没有返回语句的路径:

public static int[][] SmallestArray(int[][] A, int[][] B){
    if(A.length < B.length){
        if(A[0].length <B[0].length){
            return A;
        }
        //possibly here
    }
    else if(B.length < A.length){
        if(B[0].length <A[0].length){
            return B;
        }
        //possibly here
    }
    //definitely here!
    //in this case A and B have the same length.
    //You have return an int[][], which one will it be?
}

【讨论】:

  • 不,他们只是可能缺少回报。以同样的方式处理并处理所有其他情况可能没问题。
  • @cricket_007 你不需要possiblys。 definitely 将作为所有这些情况的后备执行。
  • 嗯,对于编译,是的,这是有道理的。对于代码中的逻辑,我会说 OP 应该包含这些返回,尽管
【解决方案2】:

您的代码未涵盖某些情况。

例如:(B.length == A.length) 不受管理。

你必须写一些 else 语句。

public static int[][] SmallestArray(int[][] A, int[][] B){
    if(A.length < B.length){
        if(A[0].length <B[0].length){
            return A;
         } else {
            //  uncovered case
         }
    }
    else if(B.length < A.length){
        if(B[0].length <A[0].length){
            return B;
         } else {
            //  uncovered case
         }
    }
    else {
       //  uncovered case
    }
}

一个好的做法是在方法的末尾只使用一个 return 语句。

public static int[][] SmallestArray(int[][] A, int[][] B){

    int[][] result = null ;
    // do the job
    return result;
}

【讨论】:

  • 这实际上是另一个答案的副本
【解决方案3】:

您违反了if else 范式。

顶级if else 应该返回不属于您的情况的值。您正在从顶级条件内的子条件(另一个 if 条件)返回值,并且编译器期望从顶级条件或方法结束处返回类型。

你可以通过任何一种方式实现它:

1.)
公共静态 int[][] SmallestArray(int[][] A, int[][] B){ 如果(A.length }
2.)
公共静态 int[][] SmallestArray(int[][] A, int[][] B){ 如果(A.length }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-29
    • 2014-08-26
    • 2019-09-14
    • 2023-01-30
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    相关资源
    最近更新 更多