0

Recently, I've learned something: I have no idea how to use toString methods.(If you've seen my last question, you'll get a prime example.)

Anyways, I was going through some unfinished programs of mine from an Intro to Java class I took last year and this one I just cannot finish. My effort to become a better programmer has faced the ultimate challenge: toString methods.

The basic overview is that I had to write a 'Grocery' store program where the ShoppingCart class was an ArrayList of Grocery Objects.

There's just one problem- when I run the program I get

Grocery.ShoppingCart@2eeb3c84

My old enemy, the toString() looks like it is required. The output I should be getting is this:

[Tomatoes: 2.76 $1.39, Mac & Cheese: 6.0, $0.89]

now if I print out the Cart ArrayList (System.out.println(Cart)) I get this:

[Tomatoes, 2.76, $1.39, Mac & Cheese, 6.0, $0.89]

Exactly the output I should be getting.

How does this happen? How can I fix this? When I print out the Cart Arraylist, I get the output I want (I still get the "Grocery.ShoppingCart@). I have to find some way to replace the "Grocery.ShoppingCart@[etc.]" with the ArrayList.

Anybody have any ideas? Thanks! -Chris

Bits of the ShoppingCart class:

ArrayList<Grocery> Cart = new ArrayList<Grocery>();
int size = Cart.size();
double tot = 0.0;
public ShoppingCart(){
}
...
public void printReceipt() {
    Grocery temp = new Grocery();
    double pr = 0.0;
    double qu = 0.0;
    String n = "";
    String con = "IF YOU SEE ME SOMETHING IS WRONG!";
    double gr = 0.0;
    for(int k = 0; k < size; k++){
        temp = Cart.get(k);
        n = temp.getName();
        qu = temp.getQuan();
        pr = temp.getPrice();
        tot = qu * pr;
        con = n + ":" + " " + qu + ", " + pr + "\t\t Total: $" + tot;
    }
    System.out.println("====RECIEPT====");
    System.out.println("Grand Total:\t" + "$" + totalPr());
}

Grocery Class Printing out ShoppingCart

public static void testShoppingCartClass ()
{
    System.out.println ("Testing ShoppingCart class\n");
    ShoppingCart myCart = new ShoppingCart();

    System.out.println ("  ShoppingCart using default constructor: ");
    System.out.println ("\t" + myCart);

    myCart.addItem (new Grocery("Tomatoes", 2.76, 1.39));
    myCart.addItem (new Grocery("Mozzarella", 0.95, 4.59));
    myCart.addItem (new Grocery("Mac & Cheese", 6, 0.89));
    System.out.println ("\n  ShoppingCart after adding three items: ");
    System.out.println ("\t" + myCart);
    myCart.removeItem (1);
    System.out.println ("\n  ShoppingCart after removing an item: ");
    System.out.println ("\t" + myCart);

    System.out.println ("\n\nPrinting receipt: \n");
    myCart.printReceipt();

    System.out.println ("\n\nDone testing ShoppingCart class\n\n");
}
Kultid_Games
  • 311
  • 1
  • 3
  • 10

3 Answers3

2

You can override toString to return whatever you want. In your case, it looks like you want to do:

class ShoppingCart {
    ArrayList<Grocery> cart;
    ...

    @Override
    public String toString() {
        return cart.toString();
    }
}
Radiodef
  • 37,180
  • 14
  • 90
  • 125
0

Java's default toString() method on any object will print out what you're seeing ("Grocery.ShoppingCart@[etc.]"). This is the Class with the object's hash code appended to the end of it.

From what I see in that output, you're calling .toString() on an instance of the ShoppingCart class which is why you're getting that output.

In order for that class to print out the contents of the ArrayList - Cart, which is a member of that class, you will need to override the toString() method of that class to print the contents of the ArrayList. Once it is overridden, your implementation of the toString() will be called rather than the default.

public String toString() {
    // return the string that you want.
}

toString() is called on shoppingCart when you call System.out.println(shoppingCart) in order to retrieve the string to print.

0

Yes, you'll need a toString() on your ShoppingCart.

If I understand what you're trying to do though, may I suggest going with a more conventional Java bean approach? Here's a simplistic view.


Bean with getter and setters. A better name for this might be Item. You can change the types as needed as well.

public class Grocery {

    public BigDecimal getQuantity() {
        return quantity;
    }

    public void setQuantity(BigDecimal quantity) {
        this.quantity = quantity;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private BigDecimal quantity;

    private BigDecimal price;

    private String name;

    @Override
    public String toString() {
        return "Grocery{" +
               "quantity=" + quantity +
               ", price=" + price +
               ", name='" + name + '\'' +
               '}';
    }
}

And your cart:

public class ShoppingCart {

    List<Grocery> contents;

    public void initialize() {
        contents = new ArrayList<Grocery>();  
    }

    public void addItem(Grocery item) {
        contents.add(item);
    }

    public void removeItem(Grocery item) {
        boolean wasRemoved = contents.remove(item);
        if (!wasRemoved) {
            System.out.println("Item not found in cart: " + item);
        }
    }

    public List<Grocery> getContents() {
        return contents;
    }

    @Override
    public String toString() {
        return "ShoppingCart{" +
               "contents=" + contents +
               '}';
    }
}

And some class to run it:

public class CartRun {

    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();
        cart.initialize(); 
        Grocery item = new Grocery();
        item.setName("Tomatoes");
        item.setPrice(BigDecimal.valueOf(2));
        item.setQuantity(BigDecimal.valueOf(3));

        cart.addItem(item);

        System.out.println("Item="+item);
        System.out.println("Cart="+cart);
    }
}

Output:

Item=Grocery{quantity=3, price=2, name='Tomatoes'}
Cart=ShoppingCart{contents=[Grocery{quantity=3, price=2, name='Tomatoes'}]}

Also, stay away from capital letters (e.g., "Cart") for variable names because it looks like a static method call by convention.

riddle_me_this
  • 8,575
  • 10
  • 55
  • 80