Again and Again打印相同的值

时间:2014-03-01 20:23:29

标签: java methods text-files

我被要求检查团队名称在我计算机上的文本上的次数。我写了代码,代码工作正常,通过计算团队名称出现的次数,但它只是继续询问团队的名称,就像我宣布的数组大小50的50倍。请帮助我。感谢。

import java.util.*;
import java.io.*;
public class worldSeries 
{
    public String getName(String teamName)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println(" Enter the Team Name : " );
        teamName = keyboard.nextLine();
        return teamName;
    }

    public int checkSeries1 () throws IOException
    {
        String teamName="";
        Scanner keyboard = new Scanner(System.in);


        String[] winners = new String[50];
        int  i = 0 ;
        File file = new File ("WorldSeriesWinners.txt");
        Scanner inputFile = new Scanner(file);
        while ( inputFile.hasNext () && i < winners.length )
        {
            winners[i] = inputFile.nextLine(); 
            i++;
        }
        inputFile.close();

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

            }
        }
        return count;

    }

    public static void main(String[]Args)
    {
        String teamName = "";
        worldSeries object1 = new worldSeries();

        try
        {
            System.out.println(" The Number of times " + object1.getName(teamName) + "won the Championship is : " +object1.checkSeries1());
        }
        catch ( IOException ioe )

        {
            System.out.println(" Exception!!! ");

            ioe.printStackTrace();
        }

    }
}

3 个答案:

答案 0 :(得分:4)

每次循环调用getName()将导致程序在每个循环中询问团队名称:

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

            }
        }

通过将getName()移出循环,它只会被调用一次(团队名称只会被请求一次):

    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++;

        }
    }

答案 1 :(得分:1)

不要在循环中调用'GetName',在循环之前调用它一次并存储结果。

答案 2 :(得分:1)

在方法checkSeries1()中,从for循环中删除getName(teamName)的方法调用,并仅在for循环外调用getName(),如下所示:

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