java:ArrayList预期的<identifier>

A-m*_*moc 3 java arraylist object identifier

我有一个名为Storage的类.存储包含一个名为Products的特殊对象的arraylist.每个产品都包含名称,价格等信息.我的代码如下:

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);
}
Run Code Online (Sandbox Code Playgroud)

每当我编译时,我都会在141-153行收到错误消息<identifier> expected.我知道这是一个基本问题,但我似乎无法解决这个问题.任何帮助深表感谢.

Cam*_*Cam 7

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

你要这个:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


pol*_*nts 5

问题是你的初始化代码不合适。你可以:

  • 将其放入构造函数或其他方法中
  • 把它放在实例初始化程序中
  • 把它作为字段初始值设定项

最后一个选项是最简单、最干净的解决方案;它看起来像这样:

List<Product> arl = new ArrayList<Product>(
  Arrays.asList(
    sprite, pepsi, orange, hershey, brownnie, apple, peanut,
    trailmix, icecream, doughnut, banana, coffee, chips
  )
);
Run Code Online (Sandbox Code Playgroud)

另请注意,我将 的类型切换arl到其 interface List<Product>。您应该尽可能尝试使用接口而不是具体的实现。