Write a program to initialize the seven wonders of the world along with their locations in two different arrays. Search for the name of a country input by the user. If found, display the name of the country along with its wonder, otherwise display "Sorry not found!". Seven wonders: CHICHEN ITZA, CHRIST THE REDEEMER, TAJ MAHAL, GREAT WALL OF CHINA, MACHU PICCHU, PETRA, COLOSSEUM Locations: MEXICO, BRAZIL, INDIA, CHINA, PERU, JORDAN, ITALY Example: Country name: INDIA Output: INDIA - TAJ MAHAL Country name: USA Output: Sorry not found!
Topic: Parallel arrays and linear search
Answer
import java.util.Scanner;
class Wonders { public static void main(String args[]) { Scanner sc = new Scanner(System.in);
String wonder[] = {"CHICHEN ITZA", "CHRIST THE REDEEMER", "TAJ MAHAL", "GREAT WALL OF CHINA", "MACHU PICCHU", "PETRA", "COLOSSEUM"};
String place[] = {"MEXICO", "BRAZIL", "INDIA", "CHINA", "PERU", "JORDAN", "ITALY"};
System.out.print("Enter the country name : "); String c = sc.nextLine().toUpperCase();
int pos = -1; for(int i = 0; i < place.length; i++) { if(place[i].equals(c)) { pos = i; break; } }
if(pos == -1) System.out.println("Sorry not found!"); else System.out.println(place[pos] + " - " + wonder[pos]); } }
This is a linear search over PARALLEL ARRAYS — two arrays whose index positions correspond, so place[2] is INDIA and wonder[2] is TAJ MAHAL. Recognising that relationship is the whole idea: you search one array and report from the other at the SAME index.
Three details carry the marks: - compare Strings with equals(), never with == - initialise pos to -1, so that "not found" can be distinguished from "found at index 0" (and MEXICO really is at index 0, so this matters here) - break as soon as a match is found, since there is nothing further to search
Converting the input with toUpperCase() lets the user type "india" and still find it, since the stored names are all capitals.
Use nextLine() rather than next(), because a country name may contain a space.
Trace the examples: INDIA is found at index 2, so the program prints INDIA - TAJ MAHAL; USA matches nothing, pos stays -1, and the program prints Sorry not found!
wonder[] String[7] - the names of the seven wonders place[] String[7] - the corresponding countries c String - the country name entered by the user pos int - index where the country is found, or -1 if absent i int - loop variable sc Scanner - object used to read input