12/13 Iterating Over a HashMap. What am I doing wrong?


#1



https://discuss.codecademy.com/c/learn-java/data-structures


My code runs but I keep getting task wrong.


Replace this line with your code.


#2

import java.util.HashMap;

public class RestaurantForEach {
public static void main(String[] args) {

	HashMap<String, Integer> restaurantMenu = new HashMap<String, Integer>();

	restaurantMenu.put("Turkey Burger", 13);
	restaurantMenu.put("Naan Pizza", 11);
	restaurantMenu.put("Cranberry Kale Salad", 10);

	System.out.println(restaurantMenu.size() );

	for (String item : restaurantMenu.keySet () ) {

		System.out.println("A " + item + " costs " + restaurantMenu.get(item) + " dollars.");

	}

}

}


#3

I got the same question, and I tried yours, but it was still asking if I have completed the for each loop correctly. Would that be some sort of bug?


#4

Im getting the same error and my code runs.

import java.util.HashMap;

public class RestaurantForEach {
public static void main(String[] args) {

	HashMap<String, Integer> restaurantMenu = new HashMap<String, Integer>();

	restaurantMenu.put("Turkey Burger", 13);
	restaurantMenu.put("Naan Pizza", 11);
	restaurantMenu.put("Cranberry Kale Salad", 10);

	System.out.println( restaurantMenu.size() ); //Prints out how many keys (3)

for (String name: restaurantMenu.keySet()) {
  
  System.out.println(name + " is age: " + restaurantMenu.get(name));
  
}

	for (String item : restaurantMenu.keySet()) {

		System.out.println("A " + item + " costs " + restaurantMenu.get(item) + " dollars.");

	}

}

}


#5

Hello.
@methodblaster74817, I see an extra space between you "restaurantMenu.keySet" and "()". I think you should remove it to work.
@aaahhh_batman aaahhh_batman, why 2 for loops in your code? you should only have the one pre-created for you. It needs to be exacly like that. Try to restart the exercise.
Anyway, Ive just completed this lesson with no problems:

import java.util.HashMap;

public class RestaurantForEach {
public static void main(String[] args) {

	HashMap<String, Integer> restaurantMenu = new HashMap<String, Integer>();

	restaurantMenu.put("Turkey Burger", 13);
	restaurantMenu.put("Naan Pizza", 11);
	restaurantMenu.put("Cranberry Kale Salad", 10);

	System.out.println(restaurantMenu.size() );

	for (String item : restaurantMenu.keySet()) {

		System.out.println("A " + item + " costs " + restaurantMenu.get(item) + " dollars.");

	}

}

}


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.