Connecting Tech Pros Worldwide Help | Site Map

Java beginner

Newbie
 
Join Date: Nov 2007
Posts: 1
#1: Nov 27 '07
Working on a project for my class and spent too long searching around on the internet trying to find the right answer...

Basically its a simple vending machine program using a hashmap.

So i got this so far...

Expand|Select|Wrap|Line Numbers
  1. public void runSimulator()
  2.     {
  3.         SoftDrink softdrink1 = new SoftDrink("A1","Coke",1.25);
  4.         SoftDrink softdrink2 = new SoftDrink("A2","Pepsi",1.25);
  5.         SoftDrink softdrink3 = new SoftDrink("A3","Sprite",1.25);
  6.         Candy candy1 = new Candy("B1","Snickers",0.75);
  7.         Candy candy2 = new Candy("B2","Crunch",0.75);
  8.         Candy candy3 = new Candy("B3","Butterfinger",0.75);
  9.  
  10.         HashMap<String,Object> vendingMap = new HashMap<String,Object>();
  11.         vendingMap.put("A1", softdrink1);
  12.         vendingMap.put("A2", softdrink2);
  13.         vendingMap.put("A3", softdrink3);
  14.         vendingMap.put("B1", candy1);
  15.         vendingMap.put("B2", candy2);
  16.         vendingMap.put("B3", candy3);
We're suppose to next just print out a list of all the items in the vending machine. But I can't figure out how to print the values of the objects.

Is there some way to just make a System.out.println( ??? (softdrink1)); and have it print out the (key, name, price)?
Expert
 
Join Date: Sep 2007
Posts: 856
#2: Nov 27 '07

re: Java beginner


There is a way to do that (sort of). You need to override the Object method toString() in your SoftDrink and Candy classes. That will then print out whatever you use in that string. If you want to print out the key that maps to that value, that's more complicated. You'll need a loop to go through the map and find which key maps to your value and save that.

Eg:
Expand|Select|Wrap|Line Numbers
  1. public class Person {
  2.   private String name;
  3.   public Person(String n){name = n;}
  4.   public String toString(){return name;}//Prototype MUST be public String toString() --No deviations permitted!
  5. };
  6. public static void main(String[] args){
  7.   Person d = new Person("Dave");
  8.   System.out.println(d); //Dave is outputted
  9. }
  10.  
Reply


Similar Java bytes