• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

problems with printing hashmap

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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???
 
Ranch Hand
Posts: 58
Eclipse IDE C++ Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 10
Chrome Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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,
 
Ranch Hand
Posts: 75
Eclipse IDE Oracle Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
reply
    Bookmark Topic Watch Topic
  • New Topic