0

Problem

I am trying to create a simple Suitcase class that wraps some Items 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)";
        }
    }
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
sqpl13
  • 15
  • 2

1 Answers1

1

Explanation

It is just this.getTotalWeight() or just getTotalWeight(). The method belongs to your Suitcase class (your this in the context), not to the items, which is of type ArrayList.

So correct it to:

public String toString() {
  if (this.items.size() == 1) {
    return this.items.size() + " item (" + this.getTotalWeight() + " kg)";
  } else {
    return this.items.size() + " items (" + this.getTotalWeight() + " kg)";
  }
}

Also, please never forget to add @Override when you override methods (such as toString), this gives you additional compiler help.


Simplifcations

While at it, you can simplify the code a bit, like so:

@Override
public String toString() {
  String itemText = items.size() == 1 ? "item" : "items";
  return "%d %s (%d kg)".formatted(items.size(), itemText, getTotalWeight());
}

The key changes are:

  • getting rid of the code duplication, the branching should only contain the part that actually changes (i.e. item vs items)
  • using ternary for readability instead of if-else
  • using formatted-strings for readability
  • removing the obsolete this. prefixes
  • adding Override
Zabuzard
  • 25,064
  • 8
  • 58
  • 82