Java数组在两个ArrayList中

3
我需要编写一个程序,让用户使用两个ArrayList(Countries和Capitals)来跟踪他所访问的所有国家及其首都。用户可以从菜单中选择三个选项之一:
1. 将一个国家及其对应的首都添加到Countries和Capitals ArrayList中。 2. 通过输入国家名称查询该国的首都。(如果已经访问过该国,则显示首都;否则给出错误消息:“您没有访问过这个国家”)。 3. 退出程序。
例如,Countries ArrayList 包含 [“England”, “France”, “Reunion”, “Nepal”],Capitals ArrayList 包含 [“London”, “Paris”, “St.Denis”, “Kathmandu”]。如果用户访问了肯尼亚并希望将其添加到ArrayList中,则Countries和Capitals ArrayList应分别变为:[“England”, “France”, “Reunion”, “Nepal”, “Kenya”] 和 [“London”, “Paris”, “St.Denis”, “Kathmandu”, “Nairobi”]。如果他想查询法国的首都,则系统应显示“巴黎”。如果用户想查找澳大利亚的首都,则系统应显示“您没有访问过这个国家”。
以下是我目前的代码:
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);
        }

    }

}

但实际上,当我输入城市的首都时,for循环显然不起作用,程序就在那里终止。

编辑:我不能使用HashMap而是要用列表。


1
除了你的主要问题外,选择一个映射,其中字符串是键,数组列表是值。 - Suresh Atta
您输入的搜索文本必须考虑大写字母检查,因此大小写敏感。 - Daniel Boncioaga
除此之外,在打印出“该国是…”后,您需要使用break;来中断,否则您将会列出所有的国家。 - Daniel Boncioaga
4个回答

3
您可以使用HashMap,以国家为key,以首都为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"

编辑:如果您仍然想使用列表,您可以按照以下方式检索相应的值。这样做的好处是它可以双向工作:

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

请注意,这仅在列表正确排序的情况下起作用(因此第一个国家与第一个首都匹配,第二个国家与第二个首都匹配,依此类推)。

2

哦,糟糕。这里有好几个问题。

首先:你的代码没有与for循环相关的问题(与你所说的问题无关)。

你的主方法只执行一个if分支,然后终止。如果你想让程序在每次完成操作后重新提示菜单,直到请求终止选项,你需要将菜单包装在一个while循环中:

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

第二点:在Java中,通常不使用成对的数组(即两个数组在语义上由其元素的位置相互关联)。您可以创建一个类:

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

或者,正如其他人建议的那样,使用Map。Map是一种数据结构,它将一个数据链接到另一个数据(在这种情况下,是首都和国家),并且还可以防止重复(在某种程度上...):

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

最后,如果你的数组是成对的,那么就没有必要同时遍历两个数组!你可以遍历国家的数组,然后将该索引移至首都的数组中:
for(int i=0; i<capitals.size();i++) {
  if(search.equals(capitals.get(i))) {
     System.out.println("The country is "+countries.get(i));
  }
}

非常感谢!我采用了您的想法,但仍然保留了两个 for 循环,并添加了 if(search.equals(ctry.get(i))) { System.out.println("The capital is "+cptl.get(j)); } - Tia
@Diksha,你自己决定吧,但要知道这在Java中不是惯用语(即不是好的实践) :) - Diego Martinoia

1

你的方法存在问题:有拥有多个首都的国家

我认为适合你需求的良好数据结构是

Map<County,Capital[]>

地图非常有用,文档在这里

额外的愚蠢想法:如果我去了梵蒂冈城国,我就同时在罗马,虽然不在意大利。好吧……如果梵蒂冈城有一个机场,否则我肯定会在意大利之前到达那里。


0
  1. 将您的代码放在 while 循环中
  2. 使用 HashMap 替代
  3. 在从用户获取输入之前先给出提示信息
  4. 从控制台获取输入时,始终尝试将整行作为输入

 

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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接