【发布时间】:2019-09-25 21:41:51
【问题描述】:
您可以在下面看到我的代码 sn-p,我在其中尝试识别给定电话号码的原产国。问题是它总是返回比较字符串值的最后一个键。
我已按 desc 顺序按值对 HashMap 进行排序,然后使用 startWith 方法将给定的 String 与 HashMap 中的每个值进行比较。
import java.util.Comparator;
import java.util.Map;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.swing.JOptionPane;
public class CountryFinder {
static Map<String, String> countriesNamesAndCodes;
public static void main(String[] args) {
countriesNamesAndCodes = new HashMap<>();
countriesNamesAndCodes.put("Greece", "30");
countriesNamesAndCodes.put("Italy", "39");
countriesNamesAndCodes.put("Germany", "49");
countriesNamesAndCodes.put("USA", "1");
countriesNamesAndCodes.put("UK", "44");
countriesNamesAndCodes.put("Bahamas", "1-242");
countriesNamesAndCodes.put("ExampleCountry", "301");
for (Entry<String, String> entry : countriesNamesAndCodes.entrySet()) {
if (entry.getValue().contains("-")) {
String tempValue = entry.getValue().replaceAll("-", "");
entry.setValue(tempValue);
}
}
countriesNamesAndCodes.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.forEach(System.out::println);
String input = String.valueOf(JOptionPane.showInputDialog("Type a telephone number"));
System.out.println(input);
System.out.println("Origin Country: " + getCountry(input));
}
private static String getCountry(String telephoneNumber) {
for (Entry<String, String> entry : countriesNamesAndCodes.entrySet()){
if (telephoneNumber.startsWith(entry.getValue())) {
return (entry.getKey());
}
}
return null;
}
}
当输入为 1242888999 或 1-242888999 时,我希望输出为 "Bahamas" ,但实际输出为 "USA"。输入 301555666 也是如此,我希望使用“ExampleCountry”而不是“Greece”。
【问题讨论】: