背景故事:我是一个网络人,在大学里很少教 OOP。现在,我被扔进了一个“一周内的 Java”工作培训课程,试图漂浮。
我需要一个 ArrayList,每个元素都具有以下四个“属性(?)”:名称、产品 ID、价格、到期日期。我想让用户选择他们想要更新的元素,然后选择他们想要更新的元素的哪个“属性”。我想了一会儿 ArrayList.set(index,element) 会起作用,但是现在我认为这将更新整个元素,而不仅仅是价格或名称(如果需要)。
我的一些代码:
ArrayList < Prod > pList = new ArrayList < Prod > ();
pList.add(new Prod("Tomato", "P101", 10, "4 days"));
//etc etc
int index = 0;
for (Prod p: pList)
{
System.out.println("");
System.out.println("Index : " + String.valueOf(index++));
System.out.println("Name : " + p.getName());
System.out.println("ID : " + p.getId());
System.out.println("Price : " + p.getPrice());
System.out.println("Expiration Date : " + p.getExpDate());
}
Scanner input = new Scanner(System. in );
System.out.println("Which Index would you like to adjust?");
int change = input.nextInt();
System.out.println("What would you like to change about Index " + change + "?");
System.out.println("Enter 1 for the Name.");
System.out.println("Enter 2 for the Product ID.");
System.out.println("Enter 3 for the Price.");
System.out.println("Enter 4 for the Expiration Date.");
int type = input.nextInt();
if (type == 1)
{
System.out.println("What would you like to change the name to?");
String newName = input.nextLine();
pList.set(change, newName);
}
我确实有 setter 和 getter,所有的作品都正确设置并且可以编译;问题是如何调整名称或 PID 等。我相信这是非常具体的,不像这里要求的提问介绍那样笼统,但我不知道如何解决这个问题;我已经为此工作了好几个小时。