Write a program to accept the names of 10 cities in a single dimensional string array and their STD (Subscribers Trunk Dialling) codes in another single dimension integer array. Search for the name of a city input by the user in the list. If found, display "Search Successful" and print the name of the city along with its STD code, or else display the message "Search unsuccessful, no such city in the list".

Java Programming Language (Article) (Program)

19

Write a program to accept the names of 10 cities in a single dimensional string array and their STD (Subscribers Trunk Dialling) codes in another single dimension integer array. Search for the name of a city input by the user in the list. If found, display "Search Successful" and print the name of the city along with its STD code, or else display the message "Search unsuccessful, no such city in the list".

Program:

import java.util.Scanner;

public class RAnsariStdCodes
{
    public static void main(String args[]) {
        final int SIZE = 10;
        Scanner in = new Scanner(System.in);
        String cities[] = new String[SIZE];
        String stdCodes[] = new String[SIZE];
        System.out.println("Enter " + SIZE +
                 " cities and their STD codes:");

        for (int i = 0;  i < SIZE; i++) {
            System.out.print("Enter City Name: ");
            cities[i] = in.nextLine();
            System.out.print("Enter its STD Code: ");
            stdCodes[i] = in.nextLine();
        }

        System.out.print("Enter name of city to search: ");
        String city = in.nextLine();

        int idx;
        for (idx = 0;  idx < SIZE; idx++) {
            if (city.compareToIgnoreCase(cities[idx]) == 0) {
                break;
            }
        }

        if (idx < SIZE) {
            System.out.println("Search Successful");
            System.out.println("City: " + cities[idx]);
            System.out.println("STD Code: " + stdCodes[idx]);
        }
        else {
            System.out.println("Search Unsuccessful");
        }
    }
}

Output:

Enter 10 cities and their STD codes:
Enter City Name: Kolkata
Enter its STD Code: 001
Enter City Name: Delhi
Enter its STD Code: 002
Enter City Name: Chennai
Enter its STD Code: 003
Enter City Name: Bangaleru
Enter its STD Code: 004
Enter City Name: Lucknow
Enter its STD Code: 005
Enter City Name: Ahemedabad
Enter its STD Code: 006
Enter City Name: Guwahati
Enter its STD Code: 007
Enter City Name: Hydrabad
Enter its STD Code: 008
Enter City Name: Lucknow
Enter its STD Code: 009
Enter City Name: Bhopal
Enter its STD Code: 010
Enter name of city to search: Kolkata
Search Successful
City: Kolkata
STD Code: 001
Press any key to continue . . .

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.