Java Hashmap -- 从标准输入到 HashMap 的键值对
Java Hashmap -- Key Value Pairs from Stdin to HashMap
Java Hashmap -- 是否可以将键值对从标准输入直接读取到哈希映射结构中?
假设用户输入
4 3
1 1
3 2
2 2
4 3
我的想法是用重复放置做某种循环。
不太确定要如何添加它们,如 int 或字符串,但请记住它们必须是对象。
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 啰嗦但你明白了。输入除整数以外的任何内容以跳出循环。不知道你想要什么。
Java Hashmap -- 是否可以将键值对从标准输入直接读取到哈希映射结构中?
假设用户输入
4 3
1 1
3 2
2 2
4 3
我的想法是用重复放置做某种循环。
不太确定要如何添加它们,如 int 或字符串,但请记住它们必须是对象。
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 啰嗦但你明白了。输入除整数以外的任何内容以跳出循环。不知道你想要什么。