【问题标题】:I was trying to directly send in values to my array as parameter but it does not work我试图直接将值作为参数发送到我的数组,但它不起作用
【发布时间】:2020-02-09 16:09:20
【问题描述】:

如果我在另一个数组中初始化这些值,然后将它传递给主函数,它就可以工作。是我做错了什么还是只是我们不能直接传递值?这是两个代码:- 使用数组传递:-

public class DDArray {
    void array(int[][] a){
        int x=a.length;
        int y=a[0].length;
        for(int i=0;i<x;i++){
            for(int j=0;j<y;j++){
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }
    public static void main(String args[]){
        DDArray ob=new DDArray();
        int[][] b={{1,2,3,4,5},{11,22,33,44,55}};
        ob.array(b);
    }
}

直接传递:-

public class DDArray {
    void array(int[][] a){
        int x=a.length;
        int y=a[0].length;
        for(int i=0;i<x;i++){
            for(int j=0;j<y;j++){
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }
    public static void main(String args[]){
        DDArray ob=new DDArray();
        ob.array({{1,2,3,4,5},{11,22,33,44,55}});
    }
}

【问题讨论】:

  • 你不能使用数组初始化器作为方法参数

标签: java arrays call-by-value


【解决方案1】:

直接调用的变化 ob.array({{1,2,3,4,5},{11,22,33,44,55}}); 到 ob.array(new int[][] { { 1, 2, 3, 4, 5 }, { 11, 22, 33, 44, 55 } });

【讨论】:

  • 非常感谢您的解决方案。连我的老师都想不通。他会很震惊?
  • 太好了,乐于助人。请也为答案投票;)
【解决方案2】:

要回答您的问题,您不能直接传递这样的值。编译器也会抱怨。此处的编译器错误非常简单 - 此处不允许使用数组初始化器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    相关资源
    最近更新 更多