我正在编写一个程序,该程序创建一个对象,该对象保存来自用户的输入并将其存储在 ArraySortedList 中。其中一个要求是检查并查看特定对象是否已在列表中。我遇到的麻烦是,每当我输入一组信息时,我都会收到错误。
//Global variables at the top
ListInterface <Golfer> golfers = new ArraySortedList < Golfer > (20);
Golfer golfer;
//Function Variables
Scanner add = new Scanner(System.in);
Golfer tempGolfer;
String name = ".";
int score;
while(!name.equals("")) //Continues until you hit enter
{
System.out.print("\nGolfer's name (press Enter to end): ");
name = add.next();
System.out.print("Golfer's score (press Enter to end): ");
score = add.nextInt();
tempGolfer = new Golfer(name,score);
if(this.golfers.contains(tempGolfer))
System.out.println("The list already contains this golfer");
else
{
this.golfers.add(this.golfer);
System.out.println("\nYou added \'Golfer(" + name + "," + score + ")\' to the list!");
}
}
错误讯息:
Exception in thread "main" java.lang.NullPointerException
at ArrayUnsortedList.find(ArrayUnsortedList.java:67)
at ArrayUnsortedList.contains(ArrayUnsortedList.java:110)
at GolfApp.addGolfer(GolfApp.java:90)
at GolfApp.mainMenu(GolfApp.java:52)
at GolfApp.main(GolfApp.java:24)
我几乎可以肯定它与引用变量的方式有关,但我不确定如何修复它,我在变量引用方面遇到了很多麻烦。
答案 0 :(得分:3)
您的高尔夫球手变量未初始化。 试试:
this.golfers.add(tempGolfer);
问候。