下面的代码是给我一个NullPointerException。问题是上下面的行:

... 
dataMap.put(nextLine[0], nextLine[6]);

什么是奇怪的是,我已经运行该代码,而上面的线和呼叫nextLine[0]nextLine[6]工作完全按预期 - 这是他们给我回一个CSV文件的内容。我声明,并与该代码初始化HashMap

HashMap<String, String> dataMap = null;

较早的方法

  String[] nextLine;
  int counter=0;
  while (counter<40) {
    counter++;

    System.out.println(counter);
    nextLine = reader.readNext(); 
    // nextLine[] is an array of values from the line
    System.out.println(nextLine[0] + " - " + nextLine[6] +" - " + "etc...");
    dataMap.put(nextLine[0], nextLine[6]);
  }
  return dataMap;
}
有帮助吗?

解决方案

HashMap<String, String> dataMap = new HashMap<String,String>();

dataMap变量没有在这一点上初始化。你应该得到一个编译器警告有关。

其他提示

其中是数据图初始化?它总是空。

要澄清,需要声明的变量,并将其设置为空。但是,你需要实例化一个新的地图,无论是一个HashMap或类似的。

e.g。

datamap = new HashMap();

(撇开泛型等)

数据图被声明但未初始化。它可以与被初始化

数据地图=新的HashMap();

那么,有在该行访问的三个对象。如果nextLine [0]和nextLine [6]是不是空的,因为上面的println调用的工作,然后离开的数据图。你做的数据图=新的HashMap(); somwehere?

嗯,究竟是什么当你这样做,你期待什么呢?

HashMap<String, String> dataMap = null;
...
dataMap.put(...)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top