Java将2个数组加在一起并返回它的总和

时间:2014-07-13 10:40:19

标签: java

我试图将2个数组加在一起并返回它的总和,但它不会产生任何输出。我想知道为什么?

public class MyProgram
{
    public static void main (String[] args)
    {
        new MyProgram().start();
    }

    public void start()
    {
        int[] ar1 = {3, 8, 4, 9, 5, 5, 23, 14};
        int[] ar2 = {33, 23, 41, 9, 17, 51, 23, 45};

        sumA(ar1, ar2);
    }

    private int[] sumA(int[] ar1, int[] ar2)
    {
        int[] sumArray = new int[0];

        for (int i = 0; i < ar1.length; i++)
        {
            sumArray[i] = ar1[i] + ar2[i];
        }
        return sumArray;
    }
}

4 个答案:

答案 0 :(得分:3)

首先,您需要正确实例化数组:

int[] sumArray = new int[ar1.length];

然后,如果你想看看结果是什么,你需要用它做一些事情(打印它可能......):

System.out.println( Arrays.toString( sumA(ar1, ar2)) );

答案 1 :(得分:2)

如果要添加不同长度的数组:

private static int[] sumA(int[] ar1, int[] ar2) {
    int[] sumArray = new int[Math.max(ar1.length, ar2.length)];

    for (int i = 0; i < sumArray.length; i++) {
        sumArray[i] = (i < ar1.length ? ar1[i] : 0) + (i < ar2.length ? ar2[i] : 0);
    }
    return sumArray;
}

如果没有,BobTheBuilder的答案就足够了。

答案 2 :(得分:1)

您的错误在这里:

int[] sumArray = new int[0]; <---

您需要使用两个参数之一的长度来实例化数组。

试试这个:

int[] sumArray = new int[ar1.length];

或者

int[] sumArray = new int[ar2.length];

如果你想显示结果:

int[] sumArray = new int[ar1.length];

for (int i = 0; i < ar1.length; i++)
{
    sumArray[i] = ar1[i] + ar2[i];
    System.out.print(sumArray[i] + " ");
}
return sumArray;

答案 3 :(得分:0)

working demo那是因为您没有在代码中编写任何system.out.println();语句。试试这段代码:

public class MyProgram
{
public static void main (String[] args)
{
    new MyProgram().start();
}

public void start()
{
    int[] ar1 = {3, 8, 4, 9, 5, 5, 23, 14};
    int[] ar2 = {33, 23, 41, 9, 17, 51, 23, 45};

    int sum[]=sumA(ar1, ar2);

    for(int i: sum)
    {
        System.out.println(i);
    }
}

private int[] sumA(int[] ar1, int[] ar2)
{
    int[] sumArray = new int[8];

    for (int i = 0; i < ar1.length; i++)
    {
        sumArray[i] = ar1[i] + ar2[i];
    }
    return sumArray;
}
}

见附图。