我是一名计算机专业的学生处理作业以下指示的数组:使用静态类作为对象
“发展,将读取输入的文本字符串并计算A的数量的应用程序, B的,C的等......你将创建一个Letter类,它将保存出现的字母和数量,以及一个LetterList类,它可以是静态的Letter对象数组。
我无法准确计算出如何使用我的静态类包含字母对象的数组。我有我的班写如下:
public class Letter {
private char letter;
private int count;
//constructor and getters and setters omitted
public void increment() {
count++;
}
static class LetterList {
private static final int MAX = 26;
private static Letter[] list;
private static int size = 0; //to prevent null pointer exception
public LetterList() {
list = new Letter[MAX];
}
public static int length() {
return size;
}
public static void addLetter(Letter letter) {
boolean added = false;
for (int i = 0; i < MAX && !added; i++) {
if (list[i] != null) {
//if the letter exists in the array increment the count
if (letter.getLetter() == list[i].getLetter()) {
list[i].increment();
added = true;
}
} else {
//if it doesn't exist add it
list[i] = letter;
added = true;
size++;
}
}
}
public static Letter getElement(int idx) {
return list[idx];
}
public static void clearList() {
size = 0;
}
}
}
因为这个类是静态的,是构造函数所需?当我想在我的LetterList类的Letter []数组中添加元素时,什么是正确的方法?让我的LetterList类本身更好吗?我感谢任何帮助和提前感谢。
我不相信你会想要在这种情况下的构造函数...只是在顶部做私人静态信[]列表=新信[MAX];'。因此它是真正的静态的,因为为了让你的代码现在能够正常工作,你需要调用构造函数。如果你想给你的'Letter []'添加一个字母,只需要做...'LetterList.addLetter(....);'。在我看来,你应该把这两门课分开。 – 3kings
静态类不需要构造函数。我认为'Map'将比数组更好地满足您的需求。 –
c0der
在这个级别上,我会发现遵循教授的建议是明智的,在这种情况下,一个静态的'Letter'对象(对于生产代码我也会做其他事情,但现在不用)。 –