CommencerCommencer gratuitement

Displaying city names

Managing sets of locations is a common task in applications like travel planning, navigation systems, or user-generated location sets. In this exercise, you will practice using an enhanced for-loop to display a set of cities. This approach ensures you can easily retrieve and process city names from a collection.

Cet exercice fait partie du cours

Input/Output and Streams in Java

Afficher le cours

Instructions

  • Use enhanced for-loop to travel through the created set cities.
  • Print each city inside the loop.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

import java.util.HashSet;

public class CityDisplay {
    public static void main(String[] args) {
        HashSet cities = new HashSet<>();

        cities.add("New York");
        cities.add("Los Angeles");
        cities.add("Chicago");

        // Use enhanced for-loop
        for (____ city: ____) {
         	// Print each city name inside the set
            System.out.println(____);
        }
    }
}
Modifier et exécuter le code