无法从Hashmap获取int

时间:2014-03-23 10:00:35

标签: java hashmap

int sayd = Integer.parseInt(args[1]);
int say = (int) Math.ceil(sayd);
Integer mapped = (Integer) GrandTheftCart.playerBounty.get(bounty);
int total = say + mapped;

所以我正在检查这样的int,每当我运行它时,当我试图检索int时,我得到一个NullPointerException。

修改

public static HashMap<String, Integer> playerBounty = new HashMap<String, Integer>();

2 个答案:

答案 0 :(得分:0)

我猜NPE被这条线抛出:

int total = say + mapped;

这是因为mappednull。由于算术运算是为数字原语定义的,因此只有java编译器执行一个魔术&#34;为你命名autoboxing。它实际上将您的行转换为以下内容:

int total = say + mapped.intValue();

如果mapped.intValue()mapped,则null非常明显地提升NPE。

现在问题是&#34;为什么值为空?&#34;我认为答案是&#34;因为您没有将非空值放到地图的适当单元格中。&#34;

现在,查看您的代码,找到您想要初始化值的位置以及未初始化的原因。然后修复bug。祝好运。

答案 1 :(得分:0)

似乎bounty未包含在playerBounty映射中,并且它返回null到mapped变量,从而导致行int total = say + mapped;中的空指针异常