Java - Array不打印我想要的值

时间:2013-12-17 01:40:41

标签: java arrays

我正在编写一个打印一个数组的程序,该数组包含作为参数传递的两个数组的值之和。当其中一个数组可能比另一个数组长时,我需要包含异常。在这种情况下,该方法应该打印两个数组共享的索引的总和,然后打印没有要添加的相应值的数组的值。

当我运行程序时,它会计算应该的总和,但是然后打印0.0而不是我想要重新打印的较长数组中的原始值。任何人都知道我的代码中我做错了什么?

    import java.util.*;

class Sum
{
    public static void main (String [] args)
    {
        double [] a1 = {2.4, 3.8};
        double [] a2 = {0.2, 9.2, 4.3, 2.8, 1.4};

        System.out.println (Arrays.toString (arraySum(a1,a2)));
    }

    public static double [] arraySum (double [] x, double [] y)
    {
        int length = 0;
        int place = 0;

        if (x.length < y.length)
        {
            double [] sumY = new double [y.length];
            length = y.length;

            for (int j = 0; j <= x.length-1; j++)
            {
                sumY [j] = x[j] + y[j];
                place++;
            }

            for (int i = place; i <= y.length - 1; i++)
            {
                sumY [place] = y[i];
            }       

            return sumY;        
        }

        if (x.length > y.length)
        {
            double [] sumX = new double [x.length];
            length = x.length;

            for (int j=0; j <= y.length-1; j++)
            {
                sumX[j] = x[j] + y[j];
                place++;
            }

            for (int i = place; i <= x.length - 1; i++)
            {
                sumX [place] = y[i];
            }

            return sumX;
        }

        else
        {
            double [] sum = new double [x.length];
            length = x.length;

            for (int i = 0; i <= length - 1; i++)
            {
                sum[i] = x[i] + y[i];
            }

            return sum;
        }

    }
}

4 个答案:

答案 0 :(得分:4)

sumX [place] = y[i];更改为sumX [i] = y[i];

答案 1 :(得分:1)

您未在后续place循环中递增for

for (int i = place; i <= x.length - 1; i++)
{
  sumX [place] = y[i];
  place++;
}

答案 2 :(得分:0)

你的if else构造看起来很可疑。似乎最后一个在你的情况下执行但不应该......

答案 3 :(得分:0)

整个arraySum方法有很多可以删除的重复代码,这会使方法更清晰,更容易理解,并且不太可能出错。

public static double [] arraySum (double [] x, double [] y)
{
    int length = Math.max(d.length, y.length);

    double[] result = new double[length]; // initializes all values to 0

    for (int i=0;i<length;i++) {
       if (i<x.length)
          result[i] = x[i]; // if x is this length use its value instead of 0
       if (i<y.length)
          result[i] += y[i]; // if y is this length add its value to the sum
    }

    return result;
}

这就是你所需要的......