Reputation: 11
Here i am trying to get key from value in Hashmap, but whenever i am trying "United Kingdom of Great Britain and Northern Ireland", it should return "GBR". It is showing me "No Records Found". How to solve this. Any help will be appreciated.
(Here if you will enter country code then it will return country name and if you will enter country NAME then it will return country CODE.)
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");
}
}
Output:
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
Upvotes: 0
Views: 4024
Reputation: 54148
You have to use String s1 = scanner.nextLine();
, instead of String s1 = scanner.next();
And it'll work and output : GBR
Because next()
(from the doc) will use by default, spaces as delimiter so it takes only the forst word
In your case after String s1 = scanner.next();
, s1
was juste United
Upvotes: 2