【问题标题】:Adding a new object to an arraylist将新对象添加到数组列表
【发布时间】:2013-12-05 01:19:48
【问题描述】:

我有一个“Bee”类型的对象,我想将它添加到我的类配置单元中的数组列表单元格中,但是在我的 getBee 的 Eclipse 侧边栏上出现编译错误“Bee 无法解析为变量”方法,我不确定我的 addBee 方法是否好。

我的代码:

import java.util.ArrayList;
public class Hive {

    ArrayList<Bee> cells = new ArrayList<Bee>();
    int Honey = 10;
    int RoyalJelly = 10;
    int Pollen = 10;    

    public void addBee(Bee b){
        cells.add(b);
    }

    public Bee getBee(int n){
        if(n < cells.size()){
            cells.get(n);
            return Bee;
        }else{
            return null;
        }
    }

    public int size(){
        return cells.size();
    }

    public void addHoney(int h){
        Honey = Honey + h;
    }

    public void addRoyalJelly(int r){
        RoyalJelly = RoyalJelly + r;
    }

    public void addPollen(int p){
        Pollen = Pollen + p;
    }

    public int takeHoney(int h2){
        if(h2 <= Honey){
            Honey = Honey - h2;
            return h2;
        }else{
            return 0;
        }
    }

    public int takeRoyalJelly(int r2){
        if(r2 <= RoyalJelly){
            RoyalJelly = RoyalJelly - r2;
            return r2;
        }else{
            return 0;
        }
    }

    public int takePollen(int p2){
        if(p2 <= Pollen){
            Pollen = Pollen - p2;
            return p2;
        }else{
            return 0;
        }
    }

    public void anotherDay(){

    }

}

【问题讨论】:

    标签: java arraylist get add


    【解决方案1】:

    您的语法在这里不正确:

    if(n < cells.size()){
        cells.get(n);
        return Bee;
    }else{
    

    您不返回类名。只需将调用结果返回给get

    if(n < cells.size()){
        return cells.get(n);
    }else{
    

    【讨论】:

      猜你喜欢
      • 2013-09-03
      • 2012-08-02
      • 2011-12-05
      • 2016-01-14
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2022-01-16
      相关资源
      最近更新 更多