得到一个;java.lang.NullPointerException“;在地图旁工作时
我正试图用这段代码编写一个简单的饮食程序。 但是我不断地得到NPE,它不断地随机中断这个过程 我的代码有什么问题?为什么我总是遇到这个错误?我该如何修复它得到一个;java.lang.NullPointerException“;在地图旁工作时,java,dictionary,nullpointerexception,hashmap,Java,Dictionary,Nullpointerexception,Hashmap,我正试图用这段代码编写一个简单的饮食程序。 但是我不断地得到NPE,它不断地随机中断这个过程 我的代码有什么问题?为什么我总是遇到这个错误?我该如何修复它 class Diet { public static void main(String[] args) { Map < Integer, String > FandVMap = new HashMap < Integer, String > (15); FandVMap.put(1, "A bo
class Diet {
public static void main(String[] args) {
Map < Integer, String > FandVMap = new HashMap < Integer, String > (15);
FandVMap.put(1, "A bowl of Salad");
/* .
.
.
*/
FandVMap.put(12, "A Banana");
//************************************************************
Map < String, Integer > CaloryMap = new HashMap < String, Integer > (30);
CaloryMap.put("An Orange", 30);
.
.
.
CaloryMap.put("A bowl of Salad", 30);
Random randomGenerator = new Random();
randomGenerator = new Random();
int i = 0;
//int rand;
while (true) {
Integer rand = 0;
rand = randomGenerator.nextInt(12);
String name = FandVMap.get(rand);
System.out.println(name);
Integer Calory = 0;
Calory = CaloryMap.get(name); // This is where the problem occurs. <<========
int Sum=0;
Sum=Sum+Calory.intValue();
System.out.println(Sum);
if (Sum > 1000) {
break;
}
}
}
}
Calory
Sum也不起作用。String name=FandVMap.get(rand)代码>
这很可能返回一个空值,您没有检查它。此外,您的变量命名不遵循标准协议,您的变量实例应该以小写字母开始以驼峰式大小写。例如,CaloryMap
应该变成CaloryMap
。这不会直接影响到这一点,但提出这一点很好 String name=FandVMap.get(兰德)代码>
这很可能返回一个空值,您没有检查它。此外,您的变量命名不遵循标准协议,您的变量实例应该以小写字母开始以驼峰式大小写。例如,CaloryMap
应该变成CaloryMap
。这不会直接影响到这一点,但提出这一点很好 方法randomGenerator.nextInt(int n)
-返回一个0(包括)到n(排除)之间的伪随机、均匀分布的int值
所以我认为在某个时刻,randomGenerator.nextInt(int n)
返回0,然后-
String name = FandVMap.get(rand)
返回null
,因此-
Calory = CaloryMap.get(name);
也被计算为null
此外,如果FandVMap
map不包含范围为1到12的键,则可能会在多种情况下发生错误。支持您的FandVMap
map不包含键4
,然后FandVMap.get(4)
还返回null
方法randomGenerator.nextInt(int n)
-返回一个0(包括)到n(排除)之间的伪随机、均匀分布的int值
所以我认为在某个时刻,randomGenerator.nextInt(int n)
返回0,然后-
String name = FandVMap.get(rand)
返回null
,因此-
Calory = CaloryMap.get(name);
也被计算为null
此外,如果FandVMap
map不包含范围为1到12的键,则可能会在多种情况下发生错误。支持您的FandVMap
map不包含键4
,然后FandVMap.get(4)
还返回null
使用randomGenerator.nextInt(12)可以得到一个从0(包括)到12(排除)的随机数
因此,如果您得到0,那么FandVMap.get(rand)将为null,因为您在HashMap中没有一个键为0的条目
rand=randomGenerator.nextInt(12)
来自JavaDoc:公共int-nextInt(int-n)
返回一个伪随机、均匀分布的int值,该值介于0(包括0)和
指定值(独占)*
使用randomGenerator.nextInt(12)可以得到一个从0(包括)到12(排除)的随机数
因此,如果您得到0,那么FandVMap.get(rand)将为null,因为您在HashMap中没有一个键为0的条目
rand=randomGenerator.nextInt(12)
来自JavaDoc:公共int-nextInt(int-n)
返回一个伪随机、均匀分布的int值,该值介于0(包括0)和
指定值(独占)*
因为您的CaloryMap
没有您期望的值。检查FandVMap
中的所有名称是否显示在CaloryMap
中。如果要将一个小的有序整数值映射到字符串,使用HashMap
是过分的。这有一个结构,叫做“数组”。你永远不会离开while循环,因为你的总和总是为零,因为你的CaloryMap
没有你期望的值。检查FandVMap
中的所有名称是否显示在CaloryMap
中。如果要将一个小的有序整数值映射到字符串,使用HashMap
是过分的。这有一个结构,叫做“数组”。你永远不会离开while循环,因为你的和总是为零谢谢。我修正了它。我不敢相信这么简单的问题让我困惑了好几个小时。而求和问题更糟糕!。谢谢,我修好了。我不敢相信这么简单的问题让我困惑了好几个小时。而求和问题更糟糕!。tnx。