简体   繁体   中英

Cannot find symbol in toString

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

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 (ie item vs items )
  • using ternary for readability instead of if-else
  • using formatted-strings for readability
  • removing the obsolete this. prefixes
  • adding Override

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM