2011-12-26 151 views
0

我是Java初学者,这是我的第一篇文章。 我找不到任何完全像我的问题,虽然这个帖子看起来类似: Why is this print line command executing twice?for循环的最后一行执行两次?

但答案并没有帮助我解决它。

我知道这可能是一些愚蠢的事情,但希望你们中的一个人可能能够指出为什么名为“matches”的数组中的最后一个条目打印出两次。

在此先感谢, 罗伯特。

这里是我的代码:

public String buildMatchList(Match[] matches) 
{ 
     fixtures = ""; 

     int i = 0; 
     for (i = 0; i < numMatches; i++) 
     { 
      if (matches[i] != null) 
      { 
       fixtures += String.format("\n%-10.10s %10.9s %15.14s", matches[i].getTeamA(), " Vs ", matches[i].getTeamB());   
      } 
     } 
     System.out.println(fixtures); 
} 

// -EDIT - 
// numMatches set in this method 

public void fillMatchArray(Team[] sortedTeams, int numTeams) 
    { 
     int homeTeam = 0; 
     int awayTeam = 0; 
     goalsA = 0; 
     goalsB = 0; 
     fixtures = ""; 
     boolean played = false; 
     matches = new Match[MAX_NUM_GAMES]; 
     for (homeTeam = 0; homeTeam < sortedTeams.length; homeTeam++) 
      for (awayTeam = homeTeam+1; awayTeam < sortedTeams.length; awayTeam++) 
      { 
       String teamA = sortedTeams[homeTeam].getTeamName(); 
       String teamB = sortedTeams[awayTeam].getTeamName();    
       matchFixtures = new Match(teamA, teamB, goalsA, goalsB, played); 
       { 
        fixtures += String.format("\n%-10.10s %10.9s %15.14s", 
          matchFixtures.getTeamA(), " Vs ", matchFixtures.getTeamB());  
       }    
       int i = 0;   
       matches[i] = matchFixtures;   
       numMatches++;   
       buildMatchList(matches); 
      } 
    } 
+0

设置变量“numMatches”在哪里? – 2011-12-26 21:17:36

+0

检查你可能有两个最后的条目是相同的,也可以在填充'匹配'的地方放一些代码片段? – havexz 2011-12-26 22:25:27

回答

6

如果它打印出两次,最有可能的解释是,最后两个条目是相同的。存在一个常见的错误,即将两个可变对象添加到集合两次,而您认为它们不同时,它们不是。

我建议你尝试在你的调试器中单步执行代码,看看它在做什么?


这是在代码中单步执行会有所帮助。则在每次时间设定数组的第一元素作为i是它总是0

  int i = 0;   
      matches[i] = matchFixtures;   
      numMatches++; 

变化到

matches[numMatches++] = matchFixtures;   
+0

嗨,谢谢你的回复。 – Robert 2011-12-27 03:03:04

+0

嗨,谢谢你的回复。 我改变: 如果(匹配[I]!= NULL) 于:(!匹配[I] .equals(空)) 如果 现在得到一个空指针错误。 – Robert 2011-12-27 03:10:18

+0

我试着用numMatches设置的代码片段将编辑添加到原始帖子中。 再次感谢。 – Robert 2011-12-27 03:45:46

-1

匹配是一个对象,所以匹配时,一个被称为引用类型。当你将它们与null进行比较时,它会将引用与null进行比较,它从不是它,因此它总是返回true。

如果你想让它的对象的内容比较空,就应该更换比赛[I]!= NULL比赛[I] .equals(空)

+0

当'[i]'为'null'时,它将成立。例如当你第一次创建数组时,它中的所有值都是'null'。如果你在'null'时匹配[i] .equals(null)',它会抛出一个NullPointerException – 2011-12-26 21:30:42