Problem
I am trying to create a simple Suitcase
class that wraps some Item
s which have a weight
.
I created a getTotalWeight()
method and now I want to call it in my toString
method but I get:
cannot find symbol
on my statement this.items.getTotalWeight()
in the toString
method. Why? What am I doing wrong?
Code
Here is the code:
Item.java
public class Item {
private int weight;
private String name;
public Item(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String toString() {
return this.name + " (" + this.weight + ")";
}
public int getWeight() {
return this.weight;
}
}
Suitcase.java
import java.util.ArrayList;
public class Suitcase {
private ArrayList<Item> items;
public Suitcase() {
this.items = new ArrayList<>();
}
public void addItem(Item item) {
this.items.add(item);
}
public int getTotalWeight() {
int totalWeight = 0;
for (Item item : items) {
totalWeight += item.getWeight();
}
return totalWeight;
}
public String toString() {
if (this.items.size() == 1) {
return this.items.size() + " item (" + this.items.getTotalWeight() + " kg)";
} else {
return this.items.size() + " items (" + this.items.getTotalWeight() + " kg)";
}
}
}