Java: expect ArrayList
•
Java
I have a class called storage Stores an ArrayList. List that contains a special object named products Each product contains name, price and other information 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",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 receive an error message on lines 141-153, indicating that < identifier > is expected I know this is a basic problem, but I can't seem to solve it Thank you for any help
Solution
You can't just call such a method in a class body. You must put the method call in another method or constructor
You want this:
class Storage{ Product sprite = new Product("sprite",30); Product pepsi = new Product("pepsi",45); Product orange = new Product("orange",36); Product hershey = new Product("hershey",33); Product brownie = new Product("brownie",41); Product apple = new Product("apple",15); Product crackers = new Product("peanut",68); Product trailmix = new Product("trailmix",45); Product icecream = new Product("icecream",28); Product doughnut = new Product("doughnut",18); Product banana = new Product("banana",32); Product coffee = new Product("coffee",40); Product chips = new Product("chips",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); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码