Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 921
Tia Avatar asked May 05 '26 05:05

Tia


2 Answers

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)

like image 197
eric.m Avatar answered May 06 '26 20:05

eric.m


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));
  }
}
like image 21
Diego Martinoia Avatar answered May 06 '26 20:05

Diego Martinoia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!