1

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

我几乎可以肯定这与变量的引用方式有关,但我不确定如何修复它,变量引用有很多麻烦。

4

1 回答 1

3

您的 golfer 变量未初始化。尝试:

this.golfers.add(tempGolfer);

问候。

于 2012-09-20T20:14:38.423 回答