K.Bowman
K.Bowman

Reputation: 87

Android Studio : List with items (objects)

I'm working on a game where player can get/make some kind of items which have specific values. For example, we have a class named "Tool" and I'd like to create some kind of array/list where I can add new items and assign specific values to each one of them.

In addition to that, I would like to somehow get all the objects from the list that have a specific value (e.g. get all the objects that have boolean owned = true and sum all their values/stats)

This is what I've got so far:

Tool Class

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);
}

Bunch of getters and setters after that...

Game Start() (creates all items and sets them to 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));

To be more specific, I would like to make a function that gets all the owned=true objects from the list and sum up their values (e.g. sum all the values: fight, resource, building etc.)

P.S. This is the first time I'm trying to code using objects and classes and I'm relatively new to Java. Tried finding the solution, but didn't exactly know how to search and after few days I gave up and decided to ask StackOverflow.

Upvotes: 0

Views: 7378

Answers (2)

Carl Poole
Carl Poole

Reputation: 2030

You might want to loop over the Tool objects in the ArrayList like this:

// 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
    }
}

Upvotes: 4

Lovekush Vishwakarma
Lovekush Vishwakarma

Reputation: 3169

do like this.

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

}
}

Upvotes: 0

Related Questions