Reputation: 15
Im working on an Digital Technology assessment. It's a Program to store a customers Pizzas, Extras and information at a Pizza store. In my confirmation window, I need to print all the pizzas he is ordering. Here are my hashmaps:
private HashMap<Integer, String> pizzas = new HashMap<Integer, String>();
private HashMap<String, Integer> pizzas_count = new HashMap<String, Integer>();
And my addPizza method, aswell as my getOrder method
public void addPizza(String name){
if(pizzas.containsValue(name)){
int count = pizzas_count.get(name);
pizzas_count.remove(name);
pizzas_count.put(name, count++);
}else{
pizzas.put(pizzas.size(), name);
pizzas_count.put(name, 1);
}
}
public String getOrder(){
String order = "";
System.out.println(pizzas.toString());
int i;
for(i = 0; i < 12; i++){
if(pizzas.get(i) != null){
System.out.println(pizzas.get(i));
order = order + pizzas_count.get(pizzas.get(i)) + " x " + pizzas.get(i) + "\n";
}
}
return order;
}
My console is showing "{0=bbq}", even after adding multiple pizzas.
The getOrder method is returning (After adding 1 pizza and 1 extra):
PIZZAS
null x null
EXTRAS
1 x pasta
Any help would be much appreciated.
Upvotes: 0
Views: 114
Reputation: 15418
After first insertion of bbq
pizza to pizza map, any subsequent insertion will just increment "bbq"
's counter as the following code suggest:
if(pizzas.containsValue(name)){ // if "bbq" already exist, increment its counter
// but is it really happening?
int count = pizzas_count.get(name);
pizzas_count.remove(name);
pizzas_count.put(name, count++);
// this line is not having any effect why?
}else{
pizzas.put(pizzas.size(), name);
pizzas_count.put(name, 1);
}
in your code pizzas_count.put(name, count++);
is not having any effect at all. This line is actually equivalent to:
{
int count = pizzas_count.get(name);
pizzas_count.put(name, count); // count wasn't changed
count = count + 1;
}
Instead do pizzas_count.put(name, ++count);
. Rest of the things are working correctly as you have written. After fixing it, the following input code:
addPizza("pizza");
addPizza("extra");
addPizza("pizza");
System.out.println(getOrder());
produces following output:
{0=pizza, 1=extra}
pizza
extra
2 x pizza
1 x extra
Upvotes: 2