Again and Again prints the same value

后端 未结 3 1821
孤街浪徒
孤街浪徒 2021-01-17 09:01

I have been asked to check the number of times a team\'s name is on the text that is on my computer. I wrote the code, the code works fine by counting the number of times th

3条回答
  •  半阙折子戏
    2021-01-17 09:46

    Calling getName() once every loop will cause the program to ask for a team name every loop:

            int count = 0;
            for ( int  index = 0 ; index < winners.length ; index ++ )
            {
                if ( getName(teamName).equals(winners[index]))
                {
                    count++;
    
                }
            }
    

    By moving getName() out of the loop, it will only be called once (and a team name will only be requested once):

        int count = 0;
        String nameOfTeam = getName(teamName); // This line runs getName() once
    
        for ( int  index = 0 ; index < winners.length ; index ++ )
        {
            if ( nameOfTeam.equals(winners[index]))
            {
                count++;
    
            }
        }
    

提交回复
热议问题