在使用地图时获取“java.lang.NullPointerException”

时间:2015-06-08 20:15:34

标签: java dictionary nullpointerexception hashmap

我正在尝试使用带有此代码的地图编写一个简单的Diet程序。 但我不断得到NPE随意中断过程。

我的代码出了什么问题?为什么我不断收到此错误以及如何解决?

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;
      }
    }
  }
}

这是我得到的输出:

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)

Calory总和也不起作用。

3 个答案:

答案 0 :(得分:6)

方法randomGenerator.nextInt(int n) - 返回0(包括)和n(不包括)之间的伪随机,均匀分布的int值。

所以我认为在某些时候randomGenerator.nextInt(int n)返回0然后 -

String name = FandVMap.get(rand)

返回null,因此 -

Calory = CaloryMap.get(name); 

也评估为null

此外,如果FandVMap映射不包含范围1到12的键,则可能会出现多个案例的错误。假设您的FandVMap地图不包含密钥4,则FandVMap.get(4)也会返回null

答案 1 :(得分:0)

String name = FandVMap.get(rand);

这很可能会返回null,您无法检查。此外,您的变量命名不遵循标准协议,您的变量实例应该以小写字母开头。例如,CaloryMap应该变为caloryMap。它并没有直接影响这一点,但提出它是件好事。

答案 2 :(得分:0)

随机的GeneGenerator.nextInt(12)你得到一个从0(包括)到12(exlusive)的随机数

所以如果你得到0 FandVMap.get(rand)将为null,因为你没有在HashMap中输入0作为键的条目。

rand = randomGenerator.nextInt(12);

  String name = FandVMap.get(rand);
  System.out.println(name);
  Integer Calory = 0;
  Calory = CaloryMap.get(name); 
  来自JavaDoc的

public int nextInt(int n)返回一个伪随机,均匀分布的int值介于0(含)和   指定值(不包括)*