这是家庭作业的一部分。
对于部分赋值,我必须创建几个数组,将它们传递给方法,在那里修改它们,并且通常使用它们。我已经成功完成了大部分工作,但最后一部分我遇到了问题。我通过四个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;
}
}
答案 0 :(得分:4)
在Wine
课程中,您已将所有属性标记为static
,即无论您创建多少个实例,都将整个课程设为一个值。每次调用时,构造函数都会覆盖所有值。
从static
中的所有4个属性中移除Wine
,以便为您创建的每个Wine
对象分别创建一个值。