Tia
Tia

Reputation: 1230

Java arrays in 2 arraylist

I have to write a program which allows the user to keep track of all the countries he has visited, and their capitals using 2 arraylists: Countries and Capitals. The user has three options to choose from a menu, he may either:

  1. Add a country and its corresponding capital in the Countries and Capital arraylists respectively.

  2. Query the system for the capital of a country by inputing the country's name. (If the country was visited, the capital should be displayed, else he should be given an error message: “You did not visit this country”).

  3. Exit the program

    For example the arraylist Countries contains [“England”, “France”, “Reunion”, “Nepal”] and the one for Capitals contains [“London”, “Paris”, “St.Denis”, “Kathmandu”]. If the user has visited Kenya whose capital is Nairobi, and wishes to add this to the arraylists, the Countries and Capitals arraylists should become: [“England”, “France”, “Reunion”, “Nepal”, “Kenya”] and Capitals contains [“London”, “Paris”, “St.Denis”, “Kathmandu”, “Nairobi”] respectively. If he wished to query for the capital of France the system should display “Paris”. If the user wishes to look for the capital of Australia – the system should display “You did not visit this country”.

So here is what I have come up so far:

import java.util.*;

public class MyClass {

    public static void main(String[] args) {

        ArrayList<String> countries = new ArrayList<String>();

        Scanner sc = new Scanner(System.in);

        String country;
        String capital;
        String search;

        countries.add("England");
        countries.add("France");
        countries.add("Reunion");
        countries.add("Nepal");

        ArrayList<String> capitals = new ArrayList<String>();

        capitals.add("London");
        capitals.add("Paris");
        capitals.add("St Denis");
        capitals.add("Kathmandu");

        System.out.println("Please choose one option:");
        System.out.println("1. Add a new country and its capital.");
        System.out.println("2. Search for the capital of a country.");
        System.out.println("3. Exit.");

        int opt = sc.nextInt();

        if (opt == 1) {
            country = sc.nextLine();
            capital = sc.nextLine();

            countries.add(country);
            capitals.add(capital);

        } else if (opt == 2) {

            System.out.println("Enter the capital of the country.");
            search = sc.next();

            for (int i = 0; i < countries.size(); i++) {
                for (int j = 0; j < capitals.size(); j++) {

                    if (search.equals(capitals.get(j))) {
                        System.out.println("The country is " + countries.get(i));

                    }

                }
            }
        } else {
            System.exit(0);
        }

    }

}

But actually, the for loop apparently does not work as when I enter the capital of the city, the program just terminates right there.

EDIT: I can't use HashMap but lists

Upvotes: 3

Views: 2045

Answers (4)

Luis Sieira
Luis Sieira

Reputation: 31522

There is a problem with you approach: There are countries with more than one capital

I think a good data structure that fits your needs would be a

Map<County,Capital[]>

Maps are very useful, the docs are here

Bonus dumb thought: If I visited Vatican City State, I'd have been at the same time in Rome, although not in Italy. Well... that would be true if the Vatican City had an airport, otherwise I surely have been in Italy right before

Upvotes: 1

afzalex
afzalex

Reputation: 8652

  1. Put your code in while loop
  2. Use HashMap instead
  3. Give message before getting input from user
  4. always try to take whole line as input when getting input from console

 

HashMap<String, String> countries = new HashMap<>();
Scanner sc = new Scanner(System.in);

String country;
String capital;
String search;

countries.put("England", "London");
countries.put("France", "Paris");
countries.put("Reunion", "St Denis");
countries.put("Nepal", "Kathmandu");

while (true) {
    System.out.println("Please choose one option:");
    System.out.println("1. Add a new country and its capital.");
    System.out.println("2. Search for the capital of a country.");
    System.out.println("3. Exit.");

    System.out.print("Enter your choice : ");
    int opt = Integer.parseInt(sc.nextLine());

    if (opt == 1) {
        System.out.print("Country : ");
        country = sc.nextLine();
        System.out.print("Capital : ");
        capital = sc.nextLine();
        countries.put(country, capital);
     } else if (opt == 2) {
        System.out.print("Enter the capital of the country : ");
        search = sc.nextLine();
        for(Map.Entry<String, String> entry : countries.entrySet()){
            if(search.equals(entry.getValue())){
                System.out.println("The country is " + entry.getKey());
                break;
            }
        }
    } else {
        System.exit(0);
    }
}

Upvotes: 0

eric.m
eric.m

Reputation: 1612

You can just use a HashMap, with the country as key and the capital as value:

HashMap<String, String> hashMap = new HashMap<String, String>();

// add data to the HashMap
hashMap.put("England", "London"); //assign value "London" to key "England"

// get data from the HashMap
hashMap.get("England"); //returns "London"

EDIT: If you still want to use lists, you can do the following to retrieve the corresponding value. The benefit of this is that it works both ways:

capitals.get(countries.indexOf("England")); //it will return "London"
countries.get(capitals.indexOf("London")); //it will return "England"

Note this will only work if the lists are properly ordered (so the first country matches the first capital, the second country matches the second capital, etc)

Upvotes: 3

Diego Martinoia
Diego Martinoia

Reputation: 4662

Oh boy. Quite a few problems here.

First of all: Your code has no problem (related to what you call the problem) with the for loop.

You main method executes exactly one of the if branches, and then terminates. If you want the program to run re-prompting the menu after every completed operation until the terminate option is requested, you need to wrap the menu in a while loop:

int opt= sc.nextInt();
while (opt != 3) {
   if (...)
}
System.exit(0);

In second place: in Java you usually don't do paired arrays (i.e. two arrays that are semantically linked by the positions of their elements). You can either create a class:

class CountryAndCapital {
  String country;
  String capital;
  //...
}
ArrayListy<CountryAndCapital> myArray = new ArrayList<>();

or, as other have suggested, use a Map, which is a data structure that links one data to another (in this case, the capital to the country), and also prevents duplicates (in a sense...):

Map<String, String> countryToCapital = new HashMap<>();
countryToCapital.put("France", "Paris");
//...

Finally: if your arrays are paired, there is no need to iterate over both! You can iterate over the country one and just take that index over to the capitals one:

for(int i=0; i<capitals.size();i++) {
  if(search.equals(capitals.get(i))) {
     System.out.println("The country is "+countries.get(i));
  }
}

Upvotes: 2

Related Questions