for循环的最后一行执行了两次?

时间:2011-12-26 21:09:37

标签: java for-loop

我是Java初学者,这是我的第一篇文章。 我找不到任何与我的问题完全相同的东西,尽管这篇文章似乎很相似 Why is this print line command executing twice?

但答案并没有帮我解决。

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

提前致谢, 罗伯特。

这是我的代码:

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

2 个答案:

答案 0 :(得分:6)

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

我建议您尝试逐步调试调试器中的代码,看看它在做什么?


这是踩过代码会有所帮助的地方。您每次都设置数组的第一个元素,因为我始终为0

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

将其更改为

matches[numMatches++] = matchFixtures;         

答案 1 :(得分:-1)

匹配是一个对象,因此匹配是一种称为引用类型。当你将它们与null进行比较时,它会将引用与null进行比较,它永远不会,因此它将始终返回true。

如果您希望它将对象的内容与null进行比较,则应将 matches [i]!= null 替换为 matches [i] .equals(null)

相关问题