gpt4 book ai didi

Java - 数组没有打印我想要的值

转载 作者:行者123 更新时间:2023-12-01 17:18:07 25 4
gpt4 key购买 nike

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

当我运行该程序时,它会按应有的方式计算总和,但随后会打印 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;
}

}
}

最佳答案

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

关于Java - 数组没有打印我想要的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20624431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com