所以我试图编写一个查看器类,然后创建一个基于这些查看器的列表作为另一个名为ViewerList的类。
通常一切都应该有效但不知何故它不允许我使用方法“toLine()”和“getName()”。如果有人在这里可以帮助我,那将是非常棒的。 在标题中,我得到的唯一错误报告是NullPointerException。
这是Viewer类:
public class Viewer {
private int points = 0;
private String name;
public Viewer(String name, int points) {
this.points = points;
this.name = name;
}
public int getPoints() {
return points;
}
public String toLine() {
String line = getName() + " " + getPoints();
return line;
}
public void addPoint(int amount){
points += amount;
}
public String getName(){
return name;
}
这是ViewerList类:
public class ViewerList {
private Viewer[] array;
private int nextFreeSlot = 0;
private int count = 0;
public ViewerList(int capacity){
array = new Viewer[capacity];
}
public void add(Viewer o){
if (nextFreeSlot == array.length) {
throw new IllegalStateException("Liste ist voll!");
}
array[nextFreeSlot] = o;
count++;
nextFreeSlot++;
}
public Viewer[] getArray(){
return array;
}
public Viewer get(int index) {
return array[index];
}
public int getCapacity() {
return array.length;
}
public int getElementCount() {
return count;
}
public void addPoints () {
if(array.length > 0){
for(Viewer v : array){
v.addPoint(1);
}
}
}
public int getPointsOf(String viewerName) {
int points = 0;
String vName = "";
for(Viewer v : array){
vName = v.getName(); // The v.getName() method is an error here
if(viewerName.equals(vName)) {
points = v.getPoints();
}
}
return points;
}
public boolean contains(String name) {
boolean contains = false;
for(Viewer v : array){
if(name.equals(v.getName())){ // also here i get the NullPointerException
contains = true;
break;
}
}
return contains;
}
}
此外,如果你需要堆栈跟踪,那么这里是:
java.lang.NullPointerException
at bot.PointList.getPointsOf(PointList.java:50)
答案 0 :(得分:0)
当您不初始化声明的变量时,会发生空指针异常。我猜你的情况是字符串名称。通过在getName()方法中添加print语句来调试代码。