我有一个基于do-while循环导航的菜单,基于整数选择。其中一个选择是在我的库存中添加新零件。当我添加它工作的部分,但后来我尝试在菜单选项“显示所有部件”(选择4)中显示它,添加的部分不存在。为什么不显示包含新值的数组?
else if(selection == 3){
System.out.println("--------------Individual Parts--------------");
System.out.println("ID: " + "\t Name: " + "\tStock Level: " + "\tUnit Price: ");
Part p = new Part();
p.printInv(); ------DOESN'T WORK HERE, AFTER ADDING NEW VALUES------
System.out.println("");
} else if(selection == 4){
Part p = new Part();
System.out.println("Add name for new part");
String n = sc.nextLine();
p.addNameToInv(n);
System.out.print("Please allocate ID. The next free ID is: ");
p.findNextID();
String n2 = sc.nextLine();
p.addIDToInv(n2);
p.printInv(); // -----WORKS HERE-----
} else if(selection >=5){
System.out.println("Invalid selection. Please try again.");
System.out.println();
System.out.println();
}
} while(selection != 0);
执行printInv()方法
public void printInv(){
for(int i=0; i<invName.length; i++){
if(invName[i] != null){
System.out.println(invID[i] + "\t " + invName[i]
+ "\t " + invSL[i] + "\t\t " + invUP[i]);
}
}
}
答案 0 :(得分:2)
您需要保存Part p
中创建的if(selection == 4)
,以便稍后在if(selection == 3)
中显示。
您现在在if(selection == 3)
中所做的是:
Part p = new Part(); //you create a new EMPTY part.
p.printInv(); //works fine, but its your newly created empty part without values.
答案 1 :(得分:0)
您需要一种方法来保持对您在&#39; if(selection == 3)&#39;中创建的声部实例的引用。
因此,您可以将它添加到像ArrayList这样的集合中,或映射一种数据结构HashMap,它保存为实例变量,然后通过此ArrayList / HashMap引用您创建的Part实例。
public class Menu {
private ArrayList<Part> listOfParts = new ArrayList<Part>();
public void partAdditionAndDisplay(int selection) {
if (selection == 3) {
Part p = listOfParts.get(index); // some required index / can use a HashMap to refer from a key
p.printInv();
System.out.println("");
} else if (selection == 4) {
Part p = new Part();
listOfParts.add(p);
p.printInv();
}
}
}