I have a hashmap with one number and one name for each. It has pre-entered values and I want to take inputs from user also. Then I want to sort it according to the number.
import java.util.HashMap;
import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;
import java.util.Scanner;
class CFG{
public static void main(String[] args) {
HashMap<String,String> hm = new HashMap<String,String>();
Scanner in = new Scanner(System.in);
hm.put("342","Shiran");
hm.put("448","Hasini");
hm.put("398","Chanchala");
hm.put("399","Priyankara ");
hm.put("350","Mayuri");
hm.put("321","Sameera");
hm.put("299","Supun");
hm.put("378","Supuni");
hm.put("384","Kavindu");
hm.put("440","Nadeeka");
System.out.println("current players and times -");
printMap(hm);
System.out.println("-------------------- \n");
System.out.println("Do you want to add more ?");
System.out.println("If yes press 1 : ");
Integer d = in.nextInt();
if(d ==1){
System.out.print("Insert a number: ");
String a = in.nextLine();
in.nextLine();// This consumes the \n character)
System.out.print("Insert name: ");
String b = in.nextLine();
hm.put(a,b);
}
Map<String, String> treeMap = new TreeMap<String, String>(hm);
printMap(treeMap);
}//main
public static void printMap(Map<String,String> map) {
Set s = map.entrySet();
Iterator it = s.iterator();
while ( it.hasNext() ) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println(key + " => " + value);
}
}
}
When user enter "100" and "John" (as an example) the output is looks like this. As you can see the name has entered but number hasn't. How can I fix this ?
=> john
299 => Supun
321 => Sameera
342 => Shiran
350 => Mayuri
378 => Supuni
384 => Kavindu
398 => Chanchala
399 => Priyankara
440 => Nadeeka
448 => Hasini