如何使用java中的循环在多个对象中分配值

时间:2022-05-26 21:42:59

I want to assign different values in multiple objects. Here is my code.

我想在多个对象中分配不同的值。这是我的代码。

SaleItem item1 = new SaleItem(); //object created SaleItem item2 = new SaleItem(); //object created SaleItem item3 = new SaleItem(); //object created //so there are 3 objects created here and I want to assign values to their variables using a loop like this

SaleItem item1 = new SaleItem(); //对象创建的SaleItem item2 = new SaleItem(); //对象创建的SaleItem item3 = new SaleItem(); //对象创建//所以这里创建了3个对象,我想使用这样的循环为它们的变量赋值

for(int i=1,i<4,i++){ item1.setPrice(input.nextInt());} // so instead of writing item1 then item2 and so on, I wanted to do this by a loop. Also I do not want to use arrays here

for(int i = 1,i <4,i ++){item1.setPrice(input.nextInt());} //所以不是写item1然后是item2,依此类推,我想通过循环来做到这一点。另外我不想在这里使用数组

1 个解决方案

#1


0  

All those classes can implement a common interface like this:

所有这些类都可以实现这样的通用接口:

public interface Item {
    public void setPrice(int x);
}

then you can use a list like this:

然后你可以使用这样的列表:

List<Item> list = new ArrayList<>();

and finally you can use a for-each loop:

最后你可以使用for-each循环:

for (Item item : list)
    item.setPrice(input.nextInt());

#1


0  

All those classes can implement a common interface like this:

所有这些类都可以实现这样的通用接口:

public interface Item {
    public void setPrice(int x);
}

then you can use a list like this:

然后你可以使用这样的列表:

List<Item> list = new ArrayList<>();

and finally you can use a for-each loop:

最后你可以使用for-each循环:

for (Item item : list)
    item.setPrice(input.nextInt());