謝謝您花時間幫助我。我有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循環中刪除返回的方面就可以正常運行。我已經嘗試了不涉及專門使用「返回」的解決方法,但無濟於事。再次感謝您的任何意見。
究竟哪一行給你NullPointerException? –
確切的錯誤是什麼? – Carcigenicate
線程「main」中的異常java.lang.NullPointerException – Uncalledfor