如何以某种格式打印出HashMap的内容?

时间:2013-12-12 14:58:27

标签: java map hashmap iteration

我不完全确定我会怎么做,这是我的代码:

public class PizzaMenu
{
    static Map<String,Pizza> namedPizzas= new HashMap<String,Pizza>();

    public static void main(String[] args)
    {

    }

    public static void addItem(String name, Pizza pizza)
    {
        namedPizzas.put(name, pizza);
    }

    public String printMenu()
    {
        /*
        String menuString="";
        for (Every menu item)

        {
            //Add name of menu item to menuString with carriage return
            //Add details of menu item (pizza.getInfo();) to menuString
        }
        */

        //return menuString
    }
}

然后我会在另一个班级打电话给System.out.println(PizzaMenu.printMenu())。我希望实现的格式如下:

/*
 * PizzaName
 *      Details
 * 
 * Next PizzaName in menu
 *      Details
 * 
 * Next PizzaName in menu
 *      Details
 * 
 * 
 * 
 */

我是否可能使用错误的数据结构进行此类操作,或者有没有办法实现此目的?

这是Pizza类的结构(对于格式不佳的道歉):

public class Pizza
{
private double cost;
private Boolean veg;
private PizzaBase base;
private List<PizzaTopping> toppings = new ArrayList<PizzaTopping>();

public Pizza(PizzaBase base, PizzaTopping topping) //Constructor for pizza with 1 topping
{
    setBase (base);
    toppings.add(topping);
}

public Pizza(PizzaBase base, PizzaTopping topping, PizzaTopping topping2) //Constructor for pizza with 2 toppings
{
    setBase (base);
    toppings.add(topping);
    toppings.add(topping2);
}

public Pizza(PizzaBase base, PizzaTopping topping, PizzaTopping topping2, PizzaTopping topping3) //Constructor for pizza with 3 toppings
{
    setBase (base);
    toppings.add(topping);
    toppings.add(topping2);
    toppings.add(topping3);
}



public double getCost()
{
    return cost;
}

public void setCost(double cost)
{
    this.cost = cost;
}

public PizzaBase getBase()
{
    return base;
}

public void setBase(PizzaBase base)
{
    this.base = base;
}

public List<PizzaTopping> getToppings()
{
    return this.toppings;
}

public String getToppingsInfo()
{
    String toppingInfo = "\n";
    PizzaTopping t;
    for (int i = 0; i<getToppings().size();i++)
    {
        t = toppings.get(i);
        toppingInfo=toppingInfo+t.getInfo();
    }

    return toppingInfo;
}


public Boolean getVeg()
{
    return veg;
}

public void setVeg(Boolean veg)
{
    this.veg = veg;
}


public double calculateCost()
{
    PizzaTopping p;
    //Loop through all ingredients and add their costs to total cost
    for (int i = 0; i<toppings.size();i++)
    {
        p = toppings.get(i);
        cost+=p.getCost();
    }

    cost+=base.getCost(); //Add pizza base cost to total cost
    return cost;
}

//Check if pizza is vegetarian depending upon its ingredients 
public Boolean isVeg()
{
    Boolean toppingCheck =true;
    Boolean baseCheck = true;
    PizzaTopping t; //Temporary value used to stored toppings being compared in for loop

    //Check each topping and check if it's suitable for vegetarians
    for (int i =0; i<toppings.size();i++)
    {
        while (toppingCheck == true)
        {
            t = toppings.get(i);
            if (t.getVeg()==false)
            {
                toppingCheck = false;
            }
        }   
    }

    //Check base to see if it's suitable for vegetarians
    if (getBase().getVeg()==false)
    {
        baseCheck = false;
    }

    //Return value depending on if all ingredients are suitable for vegetarians
    if (toppingCheck == true && baseCheck == true)
    {
        return true;
    }

    else return false;

}

public String getInfo()
{
    String vegInfo;

    if (this.isVeg()==true)
    {
        vegInfo = "Yes";
    }

    else vegInfo ="No";

    return String.format("Toppings:%s\n"+"Base:\n%s"+"\nTotal Cost:\t£%.2f"+"\nSuitable for vegetarians: %s", getToppingsInfo(), getBase().getInfo(), calculateCost(), vegInfo);
    //Return list of toppings, Total Price, vegetarian

}

}

4 个答案:

答案 0 :(得分:2)

试试这个:

String menuString="";
for (Map.Entry<String, Pizza> pizzaItem : namedPizzas.entrySet()) {
    menuString += pizzaItem.getKey() + "\n";
    menuString += "\t" + pizzaItem.getValue().getInfo() + "\n\n";
}

答案 1 :(得分:0)

public String printMenu()
    {

        String s ="";
        for (String key: namedPizzas.keySet()){
            s+= pizzaItem.getKey() + "\n";
            s+= "\t" + pizzaItem.getValue().getInfo() + "\n\n";               
        }
       return menuString
    }

答案 2 :(得分:0)

直接解决您的问题:

你需要一套钥匙。使用一组键,您还可以获得值。 HashMap#keySet应该为此工作。您可以使用for each loop遍历集合。

然后如你所说,你需要建立你的字符串并返回。把它放在一起就可以了:

public String printMenu()
{
    String menuString = "";
    for(String key : namedPizzas.keySet())
    {
        menuString += key + "\n" +
                      "\t" + namedPizzas.get(key).getInfo() + "\n\n";
    }
    return menuString;
}

我还想建议改进设计。对于像这样的事情,你应该重写Object#toString方法。尝试打印对象时,将自动调用toString方法。这样您就可以执行:System.out.println(myPizzaMenu);而不是System.out.println(myPizzaMenu.printMenu());

printMenu这个名字也具有误导性,因此也很糟糕。

答案 3 :(得分:0)

不幸的是,在将地图切换到列表后,它仍然无效。一个小时后,我发现了导致这一切的错误!感谢大家的回答,当我需要再次使用地图时,我会记住这些方法。

编辑:这是新的类结构供参考:

public class PizzaMenu
{
static List<Pizza> namedPizzas = new ArrayList<Pizza>();

public static void main(String[] args)
{

}

public static void addItem(String name, Pizza pizza)
{
    pizza.setName(name.toLowerCase());
    namedPizzas.add(pizza);
}


public static String  printMenu()
{
    String menuString="";
    Pizza p;

    //Collect all pizzas and add their information to string
    for (int i =0; i<namedPizzas.size(); i++)
    {
        p = namedPizzas.get(i);
        menuString+=p.getName().toUpperCase()+"\n"+p.getInfo()+"\n\n";
        p.resetCost();
    }

    return menuString;

}

}