Slip No 1 Q B

Q.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. [25 M]

import java.util.Hashtable;
import java.util.Scanner;
import java.util.Set;

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

        // Creating Hashtable
        Hashtable<String, String> ht = new Hashtable<>();

        // Adding city and STD code
        ht.put("Pune", "020");
        ht.put("Mumbai", "022");
        ht.put("Delhi", "011");
        ht.put("Nagpur", "0712");
        ht.put("Nashik", "0253");

        // Display Hashtable details
        System.out.println("City and STD Codes:");
        Set<String> keys = ht.keySet();
        for(String city : keys) {
            System.out.println(city + " : " + ht.get(city));
        }

        // Searching for specific city
        Scanner sc = new Scanner(System.in);
        System.out.print("\nEnter city to search STD code: ");
        String searchCity = sc.nextLine();

        if(ht.containsKey(searchCity)) {
            System.out.println("STD Code of " + searchCity + " is: " + ht.get(searchCity));
        } else {
            System.out.println("City not found in Hashtable.");
        }

        sc.close();
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top