如何使用getter和setter?半问题:如何创建结构以轻松检索数据?
在setter中设置数据后,我无法从getter中获取数据。
结构如下:
Interaction - parent class with getters and setters
Dictionary, CategoryInteraction, WordsInteraction - subclasses
这是我的代码:
public class Dictionary extends Interaction {
private String resource = "/home/kjlk/IdeaProjects/Jdf/src/fdf/res";
private File resourceFile = new File(resource);
private Scanner scanner;
private LinkedHashMap<Integer, String> categories;
public void getCategoriesFromDictionary() {
Interaction interaction = new Interaction();
try {
scanner = new Scanner(resourceFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
categories = new LinkedHashMap<>();
int categoriesCount = 1;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.startsWith("_")) {
categories.put(categoriesCount, line);
categoriesCount++;
}
}
scanner.close();
setCategories(categories);
}
}
public class Interaction {
private LinkedHashMap<Integer, String> categories;
public LinkedHashMap<Integer, String> getCategories() {
return categories;
}
public void setCategories(LinkedHashMap<Integer, String> categories) {
this.categories = categories;
}
}
public class CategoryInteraction extends Interaction {
public void printCategories() {
LinkedHashMap<Integer, String> categories = getCategories();
for (Integer key : categories.keySet()) {
System.out.println(key + ": " + categories.get(key));
}
System.out.println();
}
}
我正在获取NullPointerException:
LinkedHashMap<Integer, String> categories = getCategories();
先谢谢您!请不要让我回答有关NPE的答案!这个想法指向了工作结构。
答案 0 :(得分:0)
您需要初始化categories
。
默认情况下,其值为空。
这就是您例外的原因。