如何将数组作为参数放在java中?

时间:2014-10-06 13:10:48

标签: java arrays object

我尝试使用数组作为参数,但在尝试将数组作为参数时,我得到以下错误:

  

必需:int,int []     发现:int,int     原因:实际的参数int不能通过方法调用转换转换为int []   2个错误

源代码:

public class utopian{

    void height(int t,int[] n){

    n = new int[100];
    for (int i=0;i<t;i++){
        int k = n[i];
        if (k%2==0){
            for(int j=0;j<=k;j=j+2){
                int h=1;
                h=h*2;
                h=h+1;

            }}
            else{
                for(int j=0;j<=k;j=j+2){
                int h=1;
                h=h*2;
                h=h+1;

            }
           int h=h*2;    
            }
    System.out.println(h);  
            }        
    }

}

-

public class Solution {

    public static void main(String[] args) {
        utopian heht = new utopian();
        heht.height(2,{0,1})
}}

我想使用数组作为参数,我无法理解。

2 个答案:

答案 0 :(得分:2)

heht.height(2, new int[] {0,1})

然而,有些地方可以用较简洁的表示法,这可能会误导你:

int[] data = {0, 1};

答案 1 :(得分:0)

你可以这样做,

utopian heht = new utopian();
int array[]={0,1};//Declaration of array
heht.height(2,array)//pass array 

除了内联声明之外,不允许重用数组。

heht.height(2, new int[] {0,1});//Here you can't reuse the array in further code
//if you don't want to reuse it than go for this