对于学校,我必须编写一个程序,该程序将从文件中获取值,然后将其打印出来。我正在使用 HashMap
因为它对于存储我的数据最有意义。我遇到的问题是,当我尝试添加它时,我得到一个空指针。也许这是因为整数没有实例化,但我该怎么做呢?
这是我的代码:
public class Driver {
static ArrayList<Event> myEvents = new ArrayList<Event>();
static String[][][] counts = new String[50][1000][2];
//static ArrayList<int>[] myCounts = new ArrayList[];
//static ArrayList<String>[] myCountProfile = new ArrayList[];
@SuppressWarnings("unchecked")
static HashMap<String, Integer>[] count = new HashMap[50];
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
File input = new File("./src/Problem1/stormdata_2013.csv");
Scanner fileRead = new Scanner(input);
while (fileRead.hasNextLine()) {
String currentLine = fileRead.nextLine();
Scanner lineScan = new Scanner(currentLine).useDelimiter(",");
// Dealing with unnecessary information
for (int i = 0; i < 8; i++) {
lineScan.next();
}
String state = lineScan.next().trim();
int stateNum = Integer.parseInt(lineScan.next());
lineScan.next();
String month = lineScan.next().trim();
String type = lineScan.next().trim();
myEvents.add(new Event(type, month, state, stateNum));
count[stateNum].put(type,count[stateNum].get(type)+1);
}
}
}
最佳答案
您已经创建了一个 HashMap
的数组s:
@SuppressWarnings("unchecked")
static HashMap<String, Integer>[] count = new HashMap[50];
...但是该数组中的映射未初始化。你的数组只包含 50 null
引用。您必须首先使用 map
初始化它们,然后再添加任何内容。
if (count[stateNum] == null) {
countNum[stateNum] = new HashMap<String, Integer();
}
count[stateNum].put(type,count[stateNum].get(type)+1);
此外,我建议您创建一个 List<Map<String, Integer>>
,而不是创建原始类型的数组。正如编译器所指出的,这实际上不是类型安全的。
此外,您必须使用 String[][][]
,清楚地表明您可能没有选择最好的数据结构,这可能会对您有所帮助。我猜,你几乎肯定需要在这里单独上课。
关于Java:在 HashMap 中添加新项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22257306/