0

背景故事:我是一个网络人,在大学里很少教 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 等。我相信这是非常具体的,不像这里要求的提问介绍那样笼统,但我不知道如何解决这个问题;我已经为此工作了好几个小时。

4

5 回答 5

1
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();
Prod p = pList.get(change);

if(type==1){ 
   p.setName(input.nextLine());
}
else if(type==2){
   p.setId(input.nextLine());
}
///and so on
于 2013-07-10T03:49:04.457 回答
1
System.out.println("Which Index would you like to adjust?");
int change = input.nextInt();

Prod product = pList.get(change);

if(type==1){
   System.out.println("What would you like to change the name to?");
   String newName = input.nextLine();
   product.setName(newName);
}
于 2013-07-10T03:49:38.053 回答
1

只需获取索引处的元素change并调用相关的设置器,例如:

Prod p = pList.get(change);
switch (type)
{
    case 1:
        p.setName(newName);
        break;
    case 2:
        p.setProductId(newName);
        break;
    // etc
}
于 2013-07-10T03:51:14.203 回答
0

如果您在索引处获取对象并尝试更新它,那么它应该可以工作。像这样的东西:

//Fetch the prod need to be updated
Prod prodToUpdate = pList.get(index);
//update the attributes of the fetched prod like this
prodToUpdate.setName("updatedName");
于 2013-07-10T03:49:25.427 回答
0

您可以使用类似pList.get(change).setName()的方法来更新 Prod 对象的特定字段。

于 2013-07-10T03:50:57.607 回答