public class Test {
public static void main(String[] args) {
HashMap<String, City> cities = new HashMap<>();
cities.put("Rome", new City("Rome", "Italy", 2869461));
cities.put("Berlin", new City("Berlin", "Germany", 3610156));
cities.put("Lisbon", new City("Lisbon", "Portugal", 545245));
Iterator<String> keySetIterator = cities.keySet().iterator();
System.out.println("HashMap has " + cities.size() + " elements");
System.out.print("Enter a city to search for ");
Scanner s = new Scanner(System.in);
String searchtext = s.nextLine();
System.out.println(searchtext);
System.out.println("Key result " + cities.containsKey(searchtext));
String key = keySetIterator.next();
System.out.println("key: " + key + " value: " + cities.get(key).getName());
if (cities.get(key).getName().contains(searchtext)) {
System.out.println("Value result found " + cities.get(key).getCountry() + " " + cities.get(key).getPopulation());
}
我在main中有这个代码,我有一个只有getter,setter和constructor的类(City)。 当我运行代码时,它仅在
时运行searchtext = Rome
......如果我把
里斯本
代码没有插入最后的“if”,我也不知道为什么。有什么帮助吗?
答案 0 :(得分:0)
Asimac,
看起来你只是用
获得了第一把钥匙String key = keySetIterator.next();
我想你会想要检查所有条目而不是第一条。
考虑这样的事情:
while(keySetIterator.hasNext()){
String key = keySetIterator.next();
System.out.println("key: " + key + " value: " + cities.get(key).getName());
if (cities.get(key).getName().contains(searchtext)) {
System.out.println("Value result found " + cities.get(key).getCountry() + " " + cities.get(key).getPopulation());
}
}