Java beginner

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • m2kamp
    New Member
    • Nov 2007
    • 1

    #1

    Java beginner

    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...

    Code:
    public void runSimulator()
    	{
    		SoftDrink softdrink1 = new SoftDrink("A1","Coke",1.25);
    		SoftDrink softdrink2 = new SoftDrink("A2","Pepsi",1.25);
    		SoftDrink softdrink3 = new SoftDrink("A3","Sprite",1.25);
    		Candy candy1 = new Candy("B1","Snickers",0.75);
    		Candy candy2 = new Candy("B2","Crunch",0.75);
    		Candy candy3 = new Candy("B3","Butterfinger",0.75);
    		
    		HashMap<String,Object> vendingMap = new HashMap<String,Object>();
    	    vendingMap.put("A1", softdrink1);
    	    vendingMap.put("A2", softdrink2);
    	    vendingMap.put("A3", softdrink3);
    	    vendingMap.put("B1", candy1);
    	    vendingMap.put("B2", candy2);
    	    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.prin tln( ??? (softdrink1)); and have it print out the (key, name, price)?
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    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:
    [CODE=java]
    public class Person {
    private String name;
    public Person(String n){name = n;}
    public String toString(){retu rn name;}//Prototype MUST be public String toString() --No deviations permitted!
    };
    public static void main(String[] args){
    Person d = new Person("Dave");
    System.out.prin tln(d); //Dave is outputted
    }
    [/CODE]

    Comment

    Working...