Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: <identifier> expected with ArrayList

I have a class named Storage. Storage contains an arraylist of special objects called Products. Each product contains information such as name, price, etc. My code is as follows:

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);
}

Whenever I compile, I get an error message on lines 141-153 stating <identifier> expected. I know it's an elementary problem, but I can't seem to figure this out. Any help is much appreciated.

like image 771
A-moc Avatar asked Dec 10 '22 16:12

A-moc


1 Answers

You can't call methods like that just in the class body. You have to put methods calls in other methods, or in a constructor.

You want this:

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);
    }
}
like image 60
Cam Avatar answered Dec 14 '22 22:12

Cam