【问题标题】:how to put array as an argument in java?如何在java中将数组作为参数?
【发布时间】:2014-10-06 13:10:48
【问题描述】:

我曾尝试使用数组作为参数,但尝试将数组作为参数时出现以下错误:

必需: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})
}}

我想使用数组作为参数,但我不明白怎么做。

【问题讨论】:

  • 你必须先初始化新数组,然后再传入。
  • 使用new int[] {0, 1}。

标签: java arrays object


【解决方案1】:
heht.height(2, new int[] {0,1})

但是有些地方可以使用不那么冗长的符号,这可能会误导您:

int[] data = {0, 1};

【讨论】:

    【解决方案2】:

    你可以这样做,

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-05
      • 2011-02-17
      • 1970-01-01
      • 2011-09-25
      • 2020-10-27
      • 2018-05-29
      • 1970-01-01
      • 2011-11-24
      相关资源
      最近更新 更多