JAVA将2d数组的列作为1d数组传递 [英] JAVA pass column of 2d array as 1d array

查看:46
本文介绍了JAVA将2d数组的列作为1d数组传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将2d数组的一列作为1d数组传递.

I need to pass a column of 2d array as 1d array.

我已经通过示例进行了说明,但我不知道如何调用打印功能.

I have made this example to explain, and i don't know how to call print function.

public static void main(String[] args) {

    double[][] matrix = {{ 0,1,2},
                        {3,4,5},
                        };
}

public void print(double[] vector){

    for(int i = 0; i< vector.length ; i++){
        System.out.print(vector[i]);
    }
}

我该怎么办?

推荐答案

我需要将2d数组的一列作为1d数组传递.

I need to pass a column of 2d array as 1d array.

不,您不能直接使用2D数组调用方法,因为您的方法使用参数 double [] 而不是 double [] [] .2D数组中可以包含1D数组作为元素.因此, matrix [int index] 将为您提供一维数组以将其传递给方法.

No directly you can not call method with 2D array as your method takes parameter double[] and not double[][]. 2D array can have 1D arrays as elements in it. So, matrix[int index] will give you 1D array to pass it to the method.

因此,可以将方法声明更改为 print(double [] []向量),或者将 matrix [index] 作为方法参数传递.

So either change method declaration to print(double[][] vectors) or pass matrix[index] as method parameter.

您可以通过类的实例来调用该方法.

You can call the method by instance of you class.

YourClass obj = YourClass();
obj.print(matrix[i]);

由于您的方法需要向量,因此应使用 matrix [index] .

As your method takes vector,so matrix[index] should be used.

您可以通过在矩阵上进行迭代来构建列向量,然后将向量传递给该方法.

You can build column vector from your matrix by iterating over it and than pass vector to the method.

您需要遍历矩阵,并将所有1D数组的第一个元素收集到另一个1D数组,并将其作为方法的参数传递.

You need to loop over your matrix and collect first element of all 1D arrays to another 1D array and pass it as an argument to the method.

double[] vector = new double[matrix.length];
for(int i=0;i<matrix.length;i++) {
    double oneDArray[] = matrix[i];//Only for example
    if(oneDArray != null && oneDArray.length >0 ) {
       vector[i] = oneDArray[0];
    }
}

这篇关于JAVA将2d数组的列作为1d数组传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆