【问题标题】:How to exit a function with return type int[]?如何退出返回类型为 int[] 的函数?
【发布时间】:2021-10-09 07:32:16
【问题描述】:

我正在做一个数组右旋转的基本程序,对于基本条件,我想用return 退出函数。但是,它给出了类型无效的错误。

谁能解释为什么会这样?

import java.util.*;

public class RightRotationArray{
 public int[] solution(int[] A, int K) {
   if (K < 0 || K >= A.length) {
         return; // error showing here.
     }

     for (int i = 0; i < K; i++) {
         int last = A[A.length - 1];
         for (int j = A.length - 2; j >= 0; j--) {
             A[j + 1] = A[j];
         }

     A[0] = last;
         
     }
     return A;
 }
}

【问题讨论】:

  • 这能回答你的问题吗? Empty integer array in java
  • 这告诉你你想知道什么。 stackoverflow.com/questions/51666751/…。但是如果我将一个数组传递给一个在错误条件下返回一个空数组的函数,我会生气吗!
  • 发生这种情况是因为您没有从应该返回一个的方法返回一个 int 数组。这肯定很明显吗?

标签: java arrays


【解决方案1】:

你可以(return null)或(return new int[]{}),但最好的方法是抛出异常:

public int[] solution(int[] A, int K) throws IllegalArgumentException{
    if (K < 0 || K >= A.length) {
        throw new IllegalArgumentException("K is invalid");
    }

    for (int i = 0; i < K; i++) {
        int last = A[A.length - 1];
        System.arraycopy(A, 0, A, 1, A.length - 2 + 1);

        A[0] = last;
    }
    return A;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多