java:期望使用ArrayList
发布时间:2020-12-15 04:52:18 所属栏目:Java 来源:网络整理
导读:我有一个名为Storage的类.存储包含一个名为Products的特殊对象的arraylist.每个产品都包含名称,价格等信息.我的代码如下: class Storage{ Product sprite = new Product("sprite",1.25,30); Product pepsi = new Product("pepsi",1.85,45); Product orange
我有一个名为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",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>预期. 解决方法
你不能只在类体中调用这样的方法.您必须将方法调用放在其他方法或构造函数中.
你要这个: 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); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |