有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么要从对象数组接收NullPointException?

谢谢你抽出时间来帮我。我有三门课相互影响:分数、高尔夫球手和高尔夫测试员。Golfer包含一系列记分对象。我的问题是通过Golfer向数组中添加单个分数对象。运行GolferTester时添加分数(String,int,double,int,String)。我试着重新安排高尔夫球手。addScore()现在已经有很多次了,我在执行Golfer时仍然收到NullPointerException。findScore(字符串)

我认为这里最重要的一点是,只要我不过早结束高尔夫球手的比赛,一切都会顺利进行。返回循环的addScore()。但是,如果不停止循环,NextCore将填充整个数组,并使我查找要填充的数组插槽的方法(通过定位空插槽)在一次调用后变得无用。我将在下面显示代码。谢谢你的帮助

高尔夫球手。addscore(字符串newCourse、int newScore、double newCourse、int 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;
     }
  }
}

高尔夫球手。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;
}

高尔夫球手。getScore(字符串日期):

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

职业高尔夫测试员:

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"));  
   }
}

如前所述,只需从高尔夫球手的for循环中删除返回方面。addScore()使一切正常运行。我尝试过一些变通方法,没有特别使用“return”,但没有效果。再次感谢您的意见


共 (1) 个答案

  1. # 1 楼答案

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

    此外,稍后还将使用==来比较字符串。这行不通。你想用字符串。等于(其他字符串)