我必须编写一个程序,允许用户跟踪他访问过的所有国家,以及使用2个列表列表的国家和首都的国家和首都:国家和首都。用户可以有三种选项可供选择的菜单,他可以选择:2 ArrayList中的Java数组
分别添加一个国家及其相应的资本在国家和首都的ArrayList。
通过输入国家的名称来查询系统的国家首都。 (如果访问了国家,首都应该显示,否则他应该被给一个错误信息:“你没有访问这个国家”)。
退出程序
例如ArrayList的国家包含[“英格兰”,“法国”,“团圆”,“尼泊尔”]和一个用于首都含有[“伦敦”,“巴黎”, “圣丹尼斯”,“加德满都”]。如果用户访问了首都内罗毕的肯尼亚,并希望将其添加到数据列表中,则国家和首都数据列表应该变为:[“英格兰”,“法国”,“留尼旺”,“尼泊尔”,“肯尼亚”]和首都分别载有[“伦敦”,“巴黎”,“圣丹尼斯”,“加德满都”,“内罗毕”]。如果他想问法国首都,系统应该显示“巴黎”。如果用户希望寻找澳大利亚的首都 - 系统应显示“您未访问该国家”。
所以这是我想出迄今:
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的,但列出
除了您的主要问题,选择一个地图,其中字符串是关键和arraylist是值。 –
您对资本的检查区分大小写,因此您必须输入考虑到的搜索文本。 –
此外,打印出“国家是...”后,您需要中断;否则您将列出所有国家/地区。 –