为什么我从对象数组中接收NullPointException?

问题描述:

谢谢您花时间帮助我。我有3个与彼此互动的课程:Score,Golfer和GolferTester。高尔夫球手包含一组Score对象。我的问题是在运行GolferTester时,通过Golfer.addScore(String,int,double,int,String)将单数Score对象添加到数组中。我试图重新排列Golfer.addScore()多次,并且在执行Golfer.findScore(String)时仍然收到NullPointerException。为什么我从对象数组中接收NullPointException?

我认为这里最重要的一点是,只要我不要过早地结束Golfer.addScore()for return循环,一切都会平稳运行。但是不停止循环使用nextScore填充整个数组,并且呈现我的方法来查找哪个数组插槽要填充(通过查找空插槽),在一次调用后无用。我将在下面显示代码。谢谢您的帮助!

Golfer.addscore(字符串newCourse,整数newScore,双newCourseRating,整数newSlope,字符串newDate):

public void addScore(String newCourse, int newScore, 
    double newCourseRating, int newSlope, String newDate) 
{ 
    Score nextScore = new Score(newCourse, newDate, newScore, 
      newCourseRating, newSlope); 
    for (int i = 0; i < scores.length; i++) 
    { 
    if (scores[i] == null) 
    { 
     scores[i] = nextScore; 
     return; 
    } 
    } 
} 

Golfer.findScore(字符串日期):

private int findScore(String date) 
{ 
    int ans = 0; 
    for (int i = 0; i < scores.length; i++) 
    { 
    String iDate = scores[i].getDate(); 
    if (iDate.equals(date)) 
     ans = i; 
    } 
    if (ans == 0) 
    return -1; 
    else 
    return ans; 
} 

Golfer.getScore(字符串日期):

public Score getScore(String date) 
{ 
    int a = findScore(date); 
    return scores[a]; 
} 

class GolferTester:

public class GolferTester 
{ 
    public static void main (String[] args) 
    { 
    Golfer golfer1 = new Golfer("John", "homecourse", 4); 
    golfer1.addScore("course1", 75, 68.5, 105, "05/03/2017"); 
    System.out.println(golfer1.getScore("05/03/2017")); 
    } 
} 

如前所述,只需从Golfer.addScore()中的for循环中删除返回的方面就可以正常运行。我已经尝试了不涉及专门使用“返回”的解决方法,但无济于事。再次感谢您的任何意见。

+1

究竟哪一行给你NullPointerException? –

+1

确切的错误是什么? – Carcigenicate

+0

线程“main”中的异常java.lang.NullPointerException – Uncalledfor

在findScore中,您可以拨打String iDate = scores[i].getDate();。如果在迭代找到空(空)值之前没有找到日期,会发生什么?这是你的问题。

另外,稍后,您使用==来比较字符串。这不起作用。你想使用String.equals(otherString)

+0

对,我知道如果'字符串iDate = scores [i] .getDate();'返回一个空值,然后错误发生,但我的印象它不应该返回null。我希望解决'=='问题只会解决它,但不幸的是它不是。 – Uncalledfor