0

这是家庭作业的一部分。

对于任务的一部分,我必须创建几个数组,将它们传递给方法,在那里修改它们,并且通常与它们一起玩。我已经成功完成了大部分工作,但最后一部分有问题。我通过四个 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;
    }

}
4

1 回答 1

4

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

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

于 2013-04-24T23:16:25.257 回答