【发布时间】:2020-07-18 16:22:31
【问题描述】:
我有一个问题。当我输出我的代码时,我首先得到 Id=null Name=null 入口。问题可能出现在哪里?谢谢。
public class Solution {
HashMap<Integer, String> map;
static Integer index;
static String name;
public Solution() {
this.map = new HashMap<>();
map.put(index, name);
}
public static void main(String[] args) throws IOException {
Solution solution = new Solution();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 10; i++) {
int index = Integer.parseInt(reader.readLine());
String name = reader.readLine();
solution.map.put(index, name);
}
for (Map.Entry<Integer, String> pair : solution.map.entrySet()) {
index = pair.getKey();
name = pair.getValue();
System.out.println("Id=" + index + " Name=" + name);
}
}
}
这是输入:1 str1 2 str2 3 str3 4 str4 5 str5 6 str6 7 str7 8 str8 9 str9 10 str10
这是输出:
Id=null 名称=null
Id=1 名称=str1
Id=2 名称=str2
Id=3 名称=str3
Id=4 名称=str4
Id=5 名称=str5
Id=6 名称=str6
Id=7 名称=str7
Id=8 名称=str8
Id=9 名称=str9
Id=10 名称=str10
【问题讨论】:
-
从构造函数中去掉这行代码:
map.put(index, name); -
当您创建解决方案类的对象时,默认情况下会调用构造函数,并且您在此处编写了
map.put(index, name);这可能会给出空值。
标签: java