Java Hashmap -- Is it possible to read key value pairs from standard input directly into a hash map structure?
Say user types in
4 3
1 1
3 2
2 2
4 3
My idea is to do some sort of loop with repeated put.
Not really sure how you want to add them, as int's or Strings, but remember they have to be Objects.
class Inp {
public void scan() {
Scanner sc = new Scanner(System.in);
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
while (true) {
String sr = sc.nextLine();
String[] tk = sr.split(" ");
Integer key = 0, value = 0;
try {
key = Integer.parseInt(tk[0]);
value = Integer.parseInt(tk[1]);
}
catch (NumberFormatException e) {
break;
}
map.put(key,value);
}
}
public static void main(String[] args) {
Inp inp = new Inp();
inp.scan();
}
}
VERRRRYYYY long winded but you get the idea. Put in anything besides an integer to break out of the loop. Didn't know what you wanted.