[英]Finding Key from Hashmap using Values(with space)
在這里,我試圖從Hashmap中的值中獲取密鑰,但是每當我嘗試“大不列顛及北愛爾蘭聯合王國”時,它都應該返回“ GBR”。 它向我顯示“未找到記錄”。 如何解決這個問題。 任何幫助將不勝感激。
(在這里,如果您要輸入國家/地區代碼,則它將返回國家/地區名稱;如果您要輸入國家/地區名稱,則將返回國家/地區代碼。)
public class AppliedWithCS_1 {
public static Object getKeyFromValue(HashMap hashMap, Object value) {
for (Object o : hashMap.keySet()) {
if (hashMap.get(o).equals(value)) {
return o;
}
}
return null;
}
public static void main(String[] args) {
HashMap hashMap=new HashMap<>();
hashMap.put("AFG","Afghanistan");
hashMap.put("GBR","United Kingdom of Great Britain and Northern Ireland");
hashMap.put("IDN","Indonesia");
hashMap.put("IND","India");
System.err.println("Enter Country Code or Country Name=");
Scanner scanner=new Scanner(System.in);
String s1=scanner.next();
if(s1.length()>3&&hashMap.containsValue(s1))
{
System.out.println(getKeyFromValue(hashMap,s1));
}
else if(hashMap.containsKey(s1))
System.err.println(hashMap.get(s1));
else
System.err.println("No Records Found");
}
}
輸出:
Enter Country Code or Country Name=
Afghanistan
AFG
Enter Country Code or Country Name=
United Kingdom of Great Britain and Northern Ireland
No Records Found
您必須使用String s1 = scanner.nextLine();
,而不是String s1 = scanner.next();
它會工作並輸出: GBR
由於next()
默認情況next()
doc中的next()
將使用空格作為定界符,因此僅使用前一個單詞
在您的情況下, String s1 = scanner.next();
, s1
是Juste United
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.