我需要编写一个程序,让用户使用两个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”]。如果他想查询法国的首都,则系统应显示“巴黎”。如果用户想查找澳大利亚的首都,则系统应显示“您没有访问过这个国家”。
以下是我目前的代码:
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而是要用列表。