gpt4 book ai didi

Java,对象列表,循环更改值

转载 作者:行者123 更新时间:2023-12-02 02:23:02 24 4
gpt4 key购买 nike

我的程序有 4 个具有不同值的 Computer 对象,分别是 MakeModelProductnumber数量,和货架号。它们来自 Computer 类,该类扩展自 Product 类。我将对象添加到对象列表中,现在我需要从每个对象中获取 Shelfnumber(对象中的最后一个值),并根据这些值向它们添加不同的数量。

我的问题是,是否有任何方法可以循环遍历每个对象。当前循环只对第一个计算机对象 t1 执行此操作。现在我需要它在同一循环中获取 t2t3t4Shelfnumber

即,获取 t1 的 Shelfnumber -> 检查值是什么 -> 添加到它 -> 获取 t2Shelfnumber并做同样的事情。

public class Main {

public void computers() {
ArrayList<Object> computers = new ArrayList<Object>();
Computer t1 = new Computer("Razer", "Blade 15", "65732", 3, 12); computers.add(t1);
Computer t2 = new Computer("Apple", "MacBook Pro", "8732", 21, 15); computers.add(t2);
Computer t3 = new Computer("Asus", "Aspire 5", "7532", 5, 2); computers.add(t3);
Computer t4 = new Computer("Lenovo", "Legion 5", "3437", 2, 150); computers.add(t4);
int shelfNumber = 0;

for (int i = 0; i < computers.size(); i++) {
shelfNumber = t1.getShelfnumber();
if (shelfNumber < 10) {
shelfNumber = shelfNumber + 10;
} else if (shelfNumber > 10 && shelfNumber < 100) {
shelfNumber = shelfNumber + 30;
} else {
shelfNumber = shelfNumber + 500;
}
}
System.out.println(shelfNumber);

System.out.println(t1.toString());
System.out.println(t2.toString());
System.out.println(t3.toString());
System.out.println(t4.toString());
}

public static void main(String[] args) {
Main ohj = new Main();
ohj.computers();
}
}

最佳答案

您需要引用列表中的对象,而不是 t1直接:

for (Computer t : computers) {
shelfNumber = t.getShelfnumber();
if (shelfNumber < 10) {
shelfNumber = shelfNumber + 10;
} else if (shelfNumber > 10 && shelfNumber < 100) {
shelfNumber = shelfNumber + 30;
} else {
shelfNumber = shelfNumber + 500;
}
}

编辑:
如评论中所述,您应该定义 computers作为 List<Computer> , 不是 List<Object> .

关于Java,对象列表,循环更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66135905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com