DAVE
DAVE

Reputation: 21

Why is my toString() not working as I wanted?

The toString() method will return a String that includes all of the items in the purchases array, organized by category.

This is my output that I got wrong:

OTHER GROCERY ITEMS:
Flour     $1.89     2    $3.78

OTHER GROCERY ITEMS:
Slaw $3.73     4    $14.92   Perishable

But instead it should look something like this:

OTHER GROCERY ITEMS:
Flour     $1.89     2    $3.78
Slaw $3.73     4    $14.92   Perishable

That is, the header for a category of items should appear only once.

Here is my code:

public class GrocItem extends Item{
    
    private boolean perishable;
    
    public GrocItem(String name, double price, int qty,boolean perishable) {
        super(name, price, qty);
        this.perishable = perishable;
        perishable = false;
        
    }
    
    public boolean isPerishable() {
        return perishable;
        
    }
    
    public void setPerishable(boolean perishable) {
        this.perishable = perishable;
    }

    public String toString() {
        if(isPerishable()){
             return "\nOTHER GROCERY ITEMS:\n" + super.getName() + "\t" + "$"+getPrice() + "\t" + getQty() +"\t"+"$"+getPrice()*getQty() +"\t"+ "Perishable";
            }
         else{
                return "\nOTHER GROCERY ITEMS:\n"+super.getName() + "\t" + "$"+getPrice() + "\t" + getQty()+"\t"+"$"+getPrice()*getQty() ;
            }
    }

}

Upvotes: 0

Views: 552

Answers (2)

FaceInCake7
FaceInCake7

Reputation: 33

I don't see the tester class, so I'll make some assumptions. So, I'm assuming you have an array or arraylist of grocery items that you're looping through and printing.

When you print each grocery item, each grocery items returns the "\nOTHER GROCERY ITEM:\n" part at the beginning. So it'll print that each time.

To fix this, just get rid of that part so it's just return super.name() + ... + ... ;. Then, print the header before the loop.

Example

System.out.println("\nOTHER GROCERY ITEM:");
for (GrocItem g : yourArray) {
    System.out.println(g)
}

Upvotes: 0

Andrew
Andrew

Reputation: 49606

Don't print the header in GrocItem#toString. Print it once before the loop over the items.

System.out.println("OTHER GROCERY ITEMS:");

You don't want to use \n in toString either - avoid writing contextual things there. Today it's a table, tomorrow it could be a one-line comma separated list.

The method could be simplified a little:

public String toString() {
  return super.getName() + "\t" + "$" + getPrice() + "\t" + getQty() + "\t" + "$" + getPrice() * getQty() + (isPerishable() ? "\tPerishable" : "");
}

Notice that now only a small bit (isPerishable() ? "\tPerishable" : "") is conditional.

Upvotes: 1

Related Questions