我希望你能帮助我完成一个学校项目。我正在编写一个代码,用户输入用户在橱柜中的杂货。它还指定了它是什么类型的产品,名称,商店在哪里购买,标签,价格,数量 - 它就像一个库存。我有一个班级名称Dairy,我可以为我需要的每个输入单独创建一个getter。这很好用我设置它,有一个传递参数,当我在InputDairy方法中调用getter时它工作得很好。
但是,由于我问用户很多关于该产品的问题,我不想让10个吸气剂有一种方法只有一个,然后传递参数?这里的代码是非工作代码,我尝试在一个getter中设置所有参数,然后逐个传递参数。这不起作用。这是可能的还是我必须为我提出的每个问题设置一个吸气剂?
public static void InputDairy (Dairy DairyProducts[], Fruit FruitProducts[], Scanner input){ // START OF INPUT DAIRY
System.out.println("Let's put in some DAIRY products");
for (int i = 0; i < DairyProducts.length; i++){
System.out.println("Enter name of DIARY product");
String a = input.next();
DairyProducts[i].setDairyData(a);
System.out.println("Enter Store where you bought DIARY product");
String a = input.next();
DairyProducts[i].setDairyData(b);
System.out.println("Enter how much you paid for DIARY product");
String a = input.next();
DairyProducts[i].setDairyData(c);
System.out.println("Enter when did you buy DIARY product");
String a = input.next();
DairyProducts[i].setDairyData(d);
}
} // END OF INPUT DAIRY enter code here
public class Dairy {
private String D_NameOfDairy;
private String D_NameOfStore;
private int D_PricePaid;
private int D_DayPurchased;
private int D_BestBefore;
private int D_AmountInGrams;
private int D_Pieces;
public Dairy () {
D_NameOfDairy = "Default name of dairy";
D_NameOfStore = "Default name of store for dairy";
D_PricePaid = 0;
D_DayPurchased = 01/01/2000;
D_BestBefore = 10/10/2010;
D_AmountInGrams = 0;
D_Pieces = 0;
}
public void setDairyData (String a, String b, int c, int d){
D_NameOfDairy = a;
D_NameOfStore = b;
D_PricePaid = c;
D_DayPurchased = d;
}
}
答案 0 :(得分:3)
首先从用户那里获取所有答案,然后将这些答案传递给你的setter函数。
public static void InputDairy (Dairy DairyProducts[], Fruit FruitProducts[], Scanner input){
System.out.println("Let's put in some DAIRY products");
for (int i = 0; i < DairyProducts.length; i++){
System.out.println("Enter name of DIARY product");
String a = input.next();
System.out.println("Enter Store where you bought DIARY product");
String b = input.next();
System.out.println("Enter how much you paid for DIARY product");
String c = input.next();
System.out.println("Enter when did you buy DIARY product");
String d= input.next();
DairyProducts[i].setDairyData(a,b,c,d);
}
}