gpt4 book ai didi

java - 方法中的数组修改

转载 作者:行者123 更新时间:2023-12-01 18:49:55 24 4
gpt4 key购买 nike

这是家庭作业的一部分。

对于部分作业,我必须创建几个数组,将它们传递给方法,在那里修改它们,并且通常使用它们。我已经成功完成了大部分内容,但最后一部分遇到了问题。我通过四个 void 方法创建了四个基本类型数组。然后,我将这些数组(和对象数组)传递到另一个 void 方法中,该方法使用数组中的值构建对象数组。当我尝试使用 toString 打印这些对象的状态时,它每次都会返回数组中最后一个对象的状态(通过测试,我发现 BuildWine 方法完成后,Wine 数组的值都相当于最后创建的对象的值。但是,当在方法中打印 toString 时,它会正确打印。

我很困惑为什么在以这种方式操作时,基元数组会被正确修改,但对象数组会以如此奇怪的方式更改(它应该保持空白,给出错误,或者其他什么,而不是覆盖)具有最后创建的对象的值的所有内容)。谢谢您的帮助。

public class LabSeven {


public static void main(String[] args) {
int[] wineAges = new int[5];
String[] wineNames = new String[5];
int[] wineQuantity = new int[5];
double[] winePrice = new double[5];
Wine[] wineList = new Wine[5];

BuildAges(wineAges);
BuildNames(wineNames);
BuildQuantity(wineQuantity);
BuildPrice(winePrice);
BuildWine(wineList, wineAges, wineNames, wineQuantity, winePrice);

for(int i = 0; i < wineList.length; i++){
System.out.println(wineList[1].toString() + "\n");
}
}

public static void BuildAges(int[] wineAges){
wineAges[0] = 10;
wineAges[1] = 23;
wineAges[2] = 13;
wineAges[3] = 25;
wineAges[4] = 50;
}

public static void BuildNames(String[] wineNames){
wineNames[0] = "Chardonay";
wineNames[1] = "Riesling";
wineNames[2] = "Merlot";
wineNames[3] = "Chianti";
wineNames[4] = "Pinot Noir";
}

public static void BuildQuantity(int[] wineQuantity){
wineQuantity[0] = 10;
wineQuantity[1] = 14;
wineQuantity[2] = 4;
wineQuantity[3] = 7;
wineQuantity[4] = 1;
}

public static void BuildPrice(double[] winePrice){
winePrice[0] = 100.50;
winePrice[1] = 75.50;
winePrice[2] = 45.50;
winePrice[3] = 200.50;
winePrice[4] = 1250.50;
}

public static void BuildWine(Wine[] wineList, int[]wineAges, String[] wineNames, int[] wineQuantity, double[] winePrice){
for (int i = 0; i < wineAges.length; i++){
wineList[i] = new Wine(wineAges[i], wineNames[i], wineQuantity[i], winePrice[i]);
//System.out.println(wineList[i].toString() +"\n");
}
}
}




public class Wine {
static int age;
static String type;
static int quantity;
static double price;

public Wine(int wineAge, String wineType, int wineQuantity, double winePrice){
age = wineAge;
type = wineType;
quantity = wineQuantity;
price = winePrice;
}

public String toString(){
String status = ("Wine's Age: " + age + "\nWine's Type: " + type + "\nWine's Quantity: " + quantity + "\nWine's Price: " + price);

return status;
}

}

最佳答案

在您的 Wine 类中,您已将所有属性标记为 static,即整个类只有一个值,无论您创建多少个实例。您的构造函数在每次调用时都会覆盖所有值。

Wine 的所有 4 个属性中删除 static,以便您创建的每个 Wine 对象的每个属性都有一个值。

关于java - 方法中的数组修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16203806/

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