0

New here, so please go easy on me! I've searched other articles on the subject but can't quite find the answer i'm looking for. Hoping someone can help.

Two separate classes, object class and main method. I need to print the object details using toString, but I can't work out how to print the toppings, which are being passed as an array from the main method. The code runs ok, but when I call getToppings() from the toString method, it just prints the id of the array object name, rather than the contents of the array itself.

Can anyone help?

Thanks in advance, Marc

package toString;

/*
 * class to represent a pizza object. 
 */

public class Pizza
{

  private String name;

  private String [] toppings;

  private double price;

  public Pizza(String reqName, String [] reqToppings, double reqPrice)
  {
    name = reqName;
    toppings = reqToppings;
    price = reqPrice;
  }

  public String getName()
  {
    return name;
  }

  public String[] getToppings()
  {
    return toppings;
  }

  public double getPrice()
  {
    return price;
  }

  public String toString()
  {
    return "The pizza name is " + getName() + ", the toppings are " + getToppings() + " and the price is £" + getPrice();
  }

}

package toString;

public class TestPizza 

{
    public static void main(String[] args) 

    {

    String[] pepperoni = {"Pepperoni", "minced beef"};
    String[] diavalo = {"Pepperoni", "minced beef", "chillies"};
    String[] chicken = {"Chicken", "sweetcorn"};

    Pizza [] pizzaList = new Pizza[3];

    pizzaList[0] = new Pizza("Pepperoni", pepperoni, 6.95); 
    pizzaList[1] = new Pizza("Diavalo", diavalo, 7.95);
    pizzaList[2] = new Pizza("Chicken & Sweetcorn", chicken, 8.95);

    System.out.println(pizzaList[0].toString()); 
    System.out.println(pizzaList[1].toString());
    System.out.println(pizzaList[2].toString());

    }

}
mcooling
  • 107
  • 2
  • 14

1 Answers1

0

You have to go through array and print out every item:

 public String toString(){
    String s = "The pizza name is " + getName() + ", the toppings are: ";
    for(int i = 0; i<getToppings().size; i++){
        s += getToppings[i] + ", ";
    }
    s += "and the price is £" + getPrice();
    return s;
  }
Alex
  • 23
  • 2
  • 8