For each Loops - Java


#1

I don’t quite understand how a for each loop work?
I see in my code that it’s supposed to be for (String item : restaurantMenu.keySet()) { blah blah blah. I don’t quite understand what (String item really means.
Link-https://www.codecademy.com/courses/learn-java/lessons/data-structures/exercises/hashmap-iterating?

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.");

		}

	}
}

#2

The variable item is delcared as a string type. The HashMap is declared to have string keys.


#3

I think this will help you
Java For Loop


#4

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