繁体   English   中英

一次又一次地打印相同的值

[英]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++;

        }
    }

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

在方法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++;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM