2011-12-26 42 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