反复打印相同的值[英] Again and Again prints the same value

问题描述

我被要求检查团队名称出现在我电脑上的文字中的次数.我编写了代码,通过计算团队名称出现的次数,代码运行良好,但它只是不断询问团队名称,比如 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();
        }

    }
}

推荐答案

每个循环调用一次 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++;

        }
    }

本文地址:https://www.itbaoku.cn/post/978688.html

相关标签/搜索