我正在编写一个对象类来计算每个字母的数量,当我运行我的测试代码时,它会在“abc”传递时向我显示一个空指针异常。我无法弄清楚原因。测试代码没有错误,但我的对象类中有一些错误。
public class LetterInventory {
private static final int COUNTER = 26;
private int size = 0;
private int[] inventory;
public LetterInventory() {
inventory = new int [COUNTER];
}
public LetterInventory (String data) {
data = data.toLowerCase();
for(int i = 0; i < data.length(); i++) {
int charPosition = data.charAt(i) - 'a';
if(charPosition >= 0 && charPosition < COUNTER) {
inventory[charPosition]++;
size++;
}
}
}
答案 0 :(得分:2)
您没有在第二个构造函数中初始化数组。
public LetterInventory(String data) {
inventory = new int[COUNTER]; // <= initialization was missing
data = data.toLowerCase();
for (int i = 0; i < data.length(); i++) {
int charPosition = data.charAt(i) - 'a';
if (charPosition >= 0 && charPosition < COUNTER) {
inventory[charPosition]++;
size++;
}
}
}
答案 1 :(得分:0)
我不允许发表评论,所以你去了:
public LetterInventory(String data) {
this();
//inventory = new int[COUNTER]; // <= initialization was missing
data = data.toLowerCase();
for (int i = 0; i < data.length(); i++) {
int charPosition = data.charAt(i) - 'a';
if (charPosition >= 0 && charPosition < COUNTER) {
inventory[charPosition]++;
size++;
}
}