【问题标题】:Using arrays with toString method in Java [duplicate]在Java中使用带有toString方法的数组[重复]
【发布时间】:2019-02-28 20:06:22
【问题描述】:

这里是新人,所以请放轻松!我搜索了有关该主题的其他文章,但找不到我正在寻找的答案。希望有人可以提供帮助。

两个独立的类,对象类和主方法。我需要使用 toString 打印对象详细信息,但我不知道如何打印浇头,这些浇头是作为数组从 main 方法传递的。代码运行正常,但是当我从 toString 方法调用 getToppings() 时,它只打印数组对象名称的 id,而不是数组本身的内容。

谁能帮忙?

提前致谢, 马克

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());

    }

}

【问题讨论】:

    标签: java arrays tostring


    【解决方案1】:

    你必须遍历数组并打印出每个项目:

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

    【讨论】:

      猜你喜欢
      • 2015-06-03
      • 2012-12-07
      • 1970-01-01
      • 2014-01-19
      • 2013-06-02
      • 2012-06-09
      • 2016-08-15
      • 1970-01-01
      相关资源
      最近更新 更多