2017-02-27 87 views
0

我正在制作一款游戏,玩家可以获取/制作某种具有特定价值的物品。例如,我们有一个名为“Tool”的类,我想创建一些数组/列表,我可以在其中添加新项目并为它们中的每一个赋予特定值。Android Studio:列出物品(物品)

除此之外,我想以某种方式得到具有特定值的列表中的所有对象(例如,让所有有资= 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的一群...

游戏开始()(创建的所有项目,并将其设置为国有= 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)); 

更具体地讲,我想提出的是获取所有国有=真正的对象从一个函数列表并总结它们的值(例如,总和所有值:战斗,资源,建筑物等)

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

回答

3

你可能要循环的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 
    } 
} 
0

做到这样。

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 

} 
}