gpt4 book ai didi

java: 需要 ArrayList

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:36:38 25 4
gpt4 key购买 nike

我有一个名为 Storage 的类。 Storage 包含一个名为 Products 的特殊对象的数组列表。每个商品都包含名称、价格等信息,我的代码如下:

class Storage{

Product sprite = new Product("sprite",1.25,30);
Product pepsi = new Product("pepsi",1.85,45);
Product orange = new Product("orange",2.25,36);
Product hershey = new Product("hershey",1.50,33);
Product brownie = new Product("brownie",2.30,41);
Product apple = new Product("apple",2.00,15);
Product crackers = new Product("peanut",3.90,68);
Product trailmix = new Product("trailmix",1.90,45);
Product icecream = new Product("icecream",1.65,28);
Product doughnut = new Product("doughnut",2.75,18);
Product banana = new Product("banana",1.25,32);
Product coffee = new Product("coffee",1.30,40);
Product chips = new Product("chips",1.70,35);

ArrayList<Product> arl = new ArrayList<Product>();

//add initial elements to arraylist
arl.add(sprite);
arl.add(pepsi);
arl.add(orange);
arl.add(hershey);
arl.add(brownie);
arl.add(apple);
arl.add(peanut);
arl.add(trailmix);
arl.add(icecream);
arl.add(doughnut);
arl.add(banana);
arl.add(coffee);
arl.add(chips);
}

每当我编译时,我都会在第 141-153 行收到一条错误消息,指出 <identifier> expected .我知道这是一个基本问题,但我似乎无法弄清楚。非常感谢任何帮助。

最佳答案

您不能只在类主体中调用这样的方法。您必须将方法调用放在其他方法或构造函数中。

你想要这个:

class Storage{

Product sprite = new Product("sprite",1.25,30);
Product pepsi = new Product("pepsi",1.85,45);
Product orange = new Product("orange",2.25,36);
Product hershey = new Product("hershey",1.50,33);
Product brownie = new Product("brownie",2.30,41);
Product apple = new Product("apple",2.00,15);
Product crackers = new Product("peanut",3.90,68);
Product trailmix = new Product("trailmix",1.90,45);
Product icecream = new Product("icecream",1.65,28);
Product doughnut = new Product("doughnut",2.75,18);
Product banana = new Product("banana",1.25,32);
Product coffee = new Product("coffee",1.30,40);
Product chips = new Product("chips",1.70,35);

ArrayList<Product> arl = new ArrayList<Product>();


//constructor
protected Storage(){
//add initial elements to arraylist
arl.add(sprite);
arl.add(pepsi);
arl.add(orange);
arl.add(hershey);
arl.add(brownie);
arl.add(apple);
arl.add(peanut);
arl.add(trailmix);
arl.add(icecream);
arl.add(doughnut);
arl.add(banana);
arl.add(coffee);
arl.add(chips);
}
}

关于java: <identifier> 需要 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2576539/

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