【问题标题】:Android Studio : List with items (objects)Android Studio:包含项目(对象)的列表
【发布时间】:2017-07-18 08:08:25
【问题描述】:

我正在开发一款游戏,玩家可以在其中获取/制作某种具有特定价值的物品。例如,我们有一个名为“Tool”的类,我想创建某种数组/列表,我可以在其中添加新项目并为每个项目分配特定值。

除此之外,我想以某种方式从列表中获取所有具有特定值的对象(例如,获取所有具有 booleanowned = true 的对象并将它们的所有值/统计信息相加)

这是我目前得到的:

工具类

class Tool extends Item{
private int fight, resource, building, crafting, clothing;


public Tool(int ID, String name, boolean owned, int fight, int resource, int building, int crafting, int clothing){
    this.setID(ID);
    this.setName(name);
    this.setOwned(owned);
    this.setFight(fight);
    this.setResource(resource);
    this.setBuilding(building);
    this.setCrafting(crafting);
    this.setClothing(clothing);
}

在那之后的一堆 getter 和 setter...

Game Start()(创建所有项目并将其设置为owned=false)

public void StartGame() {

    // TOOLS

    ArrayList<Tool> tools = new ArrayList<>(); //ID, Name, Owned, Fight, Resource, Building, Crafting, Clothing
    tools.add(new Tool(1,"Hatchet",false,0,0,0,0,0));

更具体地说,我想创建一个函数,从列表中获取所有owned=true 对象并将它们的值相加(例如,将所有值相加:战斗、资源、建筑等)

附注这是我第一次尝试使用对象和类进行编码,而且我对 Java 还比较陌生。尝试找到解决方案,但不知道如何搜索,几天后我放弃并决定询问 StackOverflow。

【问题讨论】:

    标签: java android arrays oop


    【解决方案1】:

    您可能希望像这样循环 ArrayList 中的 Tool 对象:

    // A counter to keep count
    int ownedSum = 0;
    
    // For every Tool (t) in the list of Tools (tools)
    for(Tool t : tools){
    
        // Check your condition e.g: if owned is true
        if(t.getOwned()){
            ownedSum += // put getters here for the values to sum up
        }
    }
    

    【讨论】:

      【解决方案2】:

      这样做。

      int sum=0;
      for*(int i=0;i<tools.lenght;i++){
      if(tools.get(i).owned==true){
      sum=sum+tools.get(i).getFight();//here you can chnage as per your requirment
      
      }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-31
        相关资源
        最近更新 更多