簡體   English   中英

for循環的最后一行執行了兩次?

[英]Last line of for loop executed twice?

我是Java初學者,這是我的第一篇文章。 盡管這篇文章看起來很相似,但我找不到與我的問題完全相同的東西: 為什么此打印行命令執行兩次?

但是答案並沒有幫助我解決。

我知道這可能是愚蠢的,但是希望你們中的某人能夠向我指出為什么數組中名為“ 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);
            }
    }

如果打印兩次,則最可能的解釋是最后兩個條目相同。 有一個常見的錯誤,即您將可變對象兩次添加到集合中,而您認為它們是不同的,但事實並非如此。

我建議您嘗試逐步調試程序中的代碼,看看它在做什么?


這是單步執行代碼的地方。 您每次都設置數組的第一個元素,因為i始終為0

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

更改為

matches[numMatches++] = matchFixtures;         

Match是一個對象,因此Matchs被稱為引用類型。 當您將它們與null進行比較時,它將引用與null進行比較,因為它永遠不會,因此它將始終返回true。

with . 如果希望它將對象的內容與null進行比較,則應將 替換為

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM