I am trying to write a simple Diet program using maps with this code.
But I keep getting NPE which keeps interrupting the process at random.
What is wrong with my code? Why is that that I keep getting this error and how do I fix it?
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;
}
}
}
}
And here is the output I get:
A Peach
50
null
A bowl of Salad
30
A Nectarine
50
java.lang.NullPointerException
at Diet.main(gadas.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
The Calory Sum isn't working either.
CaloryMapdon't have value that you expect. Check that all names fromFandVMapare presented inCaloryMap.HashMapis overkill. There's a structure for that, and it's called "array".