• Post Reply Bookmark Topic Watch Topic
  • New Topic

problems with printing hashmap  RSS feed

 
Anissa Pary
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, in my code:


the output of the program is
{}
{}

However, I excpect it to be at least
{10= Juice 15= Milk 20 = mineral water}
what is the problem???
 
Sebanti Sanyal
Ranch Hand
Posts: 58
C++ Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Inside printRecipe(), the local variable recipe(passed as an argument) hides the class member with the same name. main() passes an empty HashMap to printRecipe() and that's what gets displayed.
 
Peeyush Bhadola
Greenhorn
Posts: 10
Chrome Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anissa,
2 things to notice-
1. Your add() method inside Drink class is populating the instance variable "recipe" (present in class Drink).
2. But your printRecipe() method is displaying the local variable recipe" which is present in the main() method, as it is being passed a parameter in the method.

There are many ways to fix it .. one of the way is to replace in main method with this statement,
 
Claudiu Chelemen
Ranch Hand
Posts: 75
Eclipse IDE Java Oracle
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would have modified the printRecipe method and given it no arguments, since the recipe is already held inside the Drink object:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!