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".
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");
}
}
}
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 . . .
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.