gpt4 book ai didi

Java:从另一个方法传递数组

转载 作者:行者123 更新时间:2023-12-02 06:27:32 25 4
gpt4 key购买 nike

我有一个项目,有四种方法。第二种和第三种方法(分别有和没有)都有数组供用户输入数据。

下面是第二种方法的示例。第三个很像

public static void billWithoutGardens()
{
Scanner input = new Scanner(System.in);

double withoutGardens[] = new double[12];

System.out.println("Please enter energy bills for year without rooftop gardens");
// 12 part array, one for each month
System.out.print("Please enter energy bill for January: ");
withoutGardens [0] = input.nextDouble();
System.out.print("Please enter energy bill for February: ");
withoutGardens [1] = input.nextDouble();
System.out.print("Please enter energy bill for March: ");
withoutGardens [2] = input.nextDouble();
System.out.print("Please enter energy bill for April: ");
withoutGardens [3] = input.nextDouble();
System.out.print("Please enter energy bill for May: ");
withoutGardens [4] = input.nextDouble();
System.out.print("Please enter energy bill for June: ");
withoutGardens [5] = input.nextDouble();
System.out.print("Please enter energy bill for July: ");
withoutGardens [6] = input.nextDouble();
System.out.print("Please enter energy bill for August: ");
withoutGardens [7] = input.nextDouble();
System.out.print("Please enter energy bill for September: ");
withoutGardens [8] = input.nextDouble();
System.out.print("Please enter energy bill for October: ");
withoutGardens [9] = input.nextDouble();
System.out.print("Please enter energy bill for November: ");
withoutGardens [10] = input.nextDouble();
System.out.print("Please enter energy bill for December: ");
withoutGardens [11] = input.nextDouble();

System.out.println(Arrays.toString(withoutGardens));


return;

我正在尝试使用第四种方法来计算两个数组中每个元素之间的差异。我不知道如何做到这一点,经过大量搜索后,我向 Stackoverflow 的好人求助。

第四种方法是这样的

public static void calculateSavings(double withoutGardens[], double withGardens[])
{

}

为了实现计算差异的目标,这是开始该方法的正确方法吗?

编辑 - 我如何将第四个方法调用回主方法?

calculateSavings(withoutGardens[], withGardens[]);

这就是我现在的情况,但我收到错误,它“无法解析为变量”。

最佳答案

创建一个与 withoutGardens 大小相同的新数组,然后执行循环并将新数组的元素设置为 withoutGardens 元素的差值>withGardens.

此外,在您的方法中,您希望返回创建的数组,即 withoutGardens,因为它是 billWithoutGardens() 内部的局部变量,并且在该方法之外不可用。

将方法签名更改为:

public static double[] billWithoutGardens()

最后一行:

return withoutGardens;

关于Java:从另一个方法传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20388716/

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