Saturday, 4 November 2023

Create a hashtable containing city name & STD code. Display the details of the hashtable. Also search for a specific city and display STD code of that city.-core java slip21

 

Create a hashtable containing city name & STD code. Display the details of the hashtable. Also search for a specific city and display STD code of that city.

 

import java.util.Hashtable;

import java.util.Scanner;

import java.io.*;

public class CitySTDHashtable {

    public static void main(String[] args) {

        Hashtable<String, String> citySTDTable = new Hashtable<>();

 

        // Populate the Hashtable with city names and STD codes

        citySTDTable.put("New York", "212");

        citySTDTable.put("Los Angeles", "213");

        citySTDTable.put("Chicago", "312");

        citySTDTable.put("San Francisco", "415");

        citySTDTable.put("Boston", "617");

 

        // Display the details of the Hashtable

        System.out.println("City STD Codes:");

        for (String city : citySTDTable.keySet()) {

            System.out.println(city + " - STD Code: " + citySTDTable.get(city));

        }

 

        // Search for a specific city and display its STD code

        Scanner scanner = new Scanner(System.in);

        System.out.print("\nEnter a city name to search for STD code: ");

        String searchCity = scanner.nextLine();

        String stdCode = citySTDTable.get(searchCity);

 

        if (stdCode != null) {

            System.out.println("STD Code for " + searchCity + ": " + stdCode);

        } else {

            System.out.println("City not found in the Hashtable.");

        }

    }

}