【问题标题】:How to call a method and pass parameter in java?如何在java中调用方法并传递参数?
【发布时间】:2017-05-03 03:58:56
【问题描述】:

代码如下。所以我预计输出是 {2 4 6 8 10},但是,当我测试它时,结果是 {1 2 3 4 5}。我现在很困惑,谁能告诉我为什么?谢谢!

public class practice{ 
    public void doubler(int[] a)
    {
        int[] b = new int[a.length];
        for(int i = 0; i< a.length; i++)
        {
            b[i] = 2*a[i];
        }
        a = b;
    }
    public static void main(String[] args) 
    {
    int[]c = {1,2,3,4,5};
        Practice w = new Practice();
        w.doubler(c);
        for(int count = 0; count<c.length; count++)
        {
            System.out.print(c[count] + " ");
        }
  }
}

【问题讨论】:

  • 怎么让你做int[] s = w.doubler(c); .....是我的问题
  • doubler 中的amain 中的c 是不同的变量。
  • 你会感到惊讶,但它与Is Java "pass-by-reference" or "pass-by-value"?重复
  • @Lashane 谢谢,这很有帮助!

标签: java methods parameters


【解决方案1】:

我认为这对你有帮助,

public class practice{ 
    public int[] doubler(int[] a)
    {
        int[] b = new int[a.length];
        for(int i = 0; i< a.length; i++)
        {
            b[i] = 2*a[i];
        }
        return b;
    }
    public static void main(String[] args) 
    {
    int[]c = {1,2,3,4,5};
        Practice w = new Practice();
        int[] s=w.doubler(c);
        for(int count = 0; count<s.length; count++)
        {
            System.out.print(s[count] + " ");
        }
    } 
}

你的情况,你没有将相乘的数组返回给int[] s

【讨论】:

  • 我做到了,但它仍然给我相同的输出......(1 2 3 4 5)
  • 你是否像这样循环输出 int[] , System.out.print(s[count] + " ");
  • @CherylLiang 从字面上复制并粘贴他的代码,它就可以工作了。
【解决方案2】:

由于 double 是 void 方法,所以下面的方法不起作用

int[] s=w.doubler(c);

因为它会类似于

int[] s= void; // wrong

改变方法的返回类型

public int[] doubler(int[] a) 

方法完成后立即返回数组 b

【讨论】:

    【解决方案3】:

    将方法doubler改为:

    public int[] doubler(int[] a)
        {
            int[] b = new int[a.length];
            for(int i = 0; i< a.length; i++)
            {
                b[i] = 2*a[i];
            }
            return b;
        }
    

    这将为您提供新数组b

    【讨论】:

    • 感谢您的回复。我做到了,但它仍然打印出原始的 c 数组。我觉得我的主要方法有问题。
    • 你必须在main方法中做c = w.doubler(c);
    猜你喜欢
    • 2019-04-05
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多