gpt4 book ai didi

java - 引用麻烦

转载 作者:行者123 更新时间:2023-11-29 05:55:01 26 4
gpt4 key购买 nike

我正在编写一个程序来创建一个对象,该对象保存用户的输入并将其存储在 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)

我几乎可以肯定这与引用变量的方式有关,但我不确定如何解决它,我在变量引用方面遇到了很多麻烦。

最佳答案

您的高尔夫球手变量未初始化。尝试:

this.golfers.add(tempGolfer);

问候。

关于java - 引用麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12520174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com