调用两次而不是一次键入团队名称 [英] Invoking to type the team name twice instead of once

查看:163
本文介绍了调用两次而不是一次键入团队名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已要求我检查在计算机上创建的文本文件中是否存在团队名称.我已经编写了完整的代码,但是输出总是调用我输入团队名称两次,然后计算文件中团队名称出现的次数.请务必查看此信息,并让我知道.谢谢.

I have been asked to check if the team name is present in the text file I had created on my computer. I have written the complete code but the output is always invoking me type the name of the team twice before counting the number of times the team's name is present in the file. Please do see this, and let me know. 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="";


        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;
        String nameOfTeam = getName(teamName);

        for ( int  index = 0 ; index < winners.length ; index ++ )
        {
            if ( nameOfTeam.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();
        }

    }
}

推荐答案

您的代码正在执行此操作:

Your code is doing this:

System.out.println(" The Number of times " + object1.getName(teamName) + "won the Championship is : " +object1.checkSeries1());

您的getName方法提示输入名称-在上一行中直接调用它,也间接调用它(在同一行中的checkSeries1中).因此,这意味着该行被两次调用了.

Your getName method is prompting for the name- it is being called directly in the line above, and it is also called indirectly (inside checkSeries1 on the same line). So that means it's being called twice in that line...

您将需要重新考虑提示的完成位置,并进行一些重构以解决该问题.

You will want to reconsider where prompting is done and do some refactoring to fix it.

这篇关于调用两次而不是一次键入团队名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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