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

查看:121
本文介绍了Again and Again打印相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 the team name has appeared but it just keeps on asking the name of the team, like 50 times since the size of the array i declared is 50. Please help me out. Thanks.

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()一旦每个循环都会导致程序在每个循环中询问一个团队名称:

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

            }
        }

移动 getName()离开循环,它只会被调用一次(团队名称只会被请求一次):

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

        }
    }

这篇关于Again and Again打印相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆