繁体   English   中英

如何计算一个单词在文本文件中出现的次数

[英]How to count the number of times a word is in the text file

我被要求编写一个程序来检查我在计算机上创建的文本文件中是否存在团队名称,并说明它在文件中重复了多少次? 你能帮我一下吗? 我已经编写了代码来检查这个词是否存在,但不知道如何检查它出现的次数。

import java.util.*;
import java.io.*;
public class worldSeries 
{
    public boolean checkSeries () throws IOException
    {

        Scanner keyboard = new Scanner(System.in);

        boolean result = false;

        String[] winners = new String[200];

        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();

        System.out.println(" Enter the Team's name you want to check : " );

        String teamName = keyboard.nextLine();

        for ( int  index = 0 ; index < winners.length ; index ++ )
        {
            if ( teamName.equals(winners[index]))
            {
                result = true;
            }


        }
        return result;
    }

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

        try
        {
            System.out.println(" The search result for the Team's name is : " + object1.checkSeries ());
        }
        catch (IOException ioe)
        {
            System.out.println(" Exception!!! ");

            ioe.printStackTrace();
        }

    }
}

基本上你可以重用你已经存在的for循环

for(int  index = 0 ; index < winners.length ; index++){
        if ( teamName.equals(winners[index])){
            result = true;
        }
}

引入一个变量counter ,该counter初始化为 0,如果团队名称匹配则递增。

此外,我建议重新构建您的代码。

  1. 以单独的方法读取文件的内容。 让该方法返回一个String[]存储到String[] winners
  2. 向用户询问团队名称。
  3. 检查数组winners是否包含团队名称。 这已经发生在您的方法checkSeries() 正如您可以从我之前的评论中想象的那样,我会将 Scanner 代码移动到 1 中描述的方法。请记住,方法名称应该描述方法中发生的事情 - 因此checkSeries()应该只检查并返回是或否。
  4. 在计数的新方法中重用checkSeries()的 for 循环。 仅当checkSeries()返回 true 时才需要调用此方法。

而不是result = true; 你可以在循环内增加一个计数器。

例如:

    int counter = 0;
    for ( int  index = 0 ; index < winners.length ; index ++ )
    {
        if ( teamName.equals(winners[index]))
        {
            counter = counter + 1;
        }
    }

然后您可以将方法的返回类型更改为int并返回counter

只返回 true / false 的方法可以使用新方法。 如果返回值为 0,则返回 false,否则返回 true。

您可以使用以“key”作为单词和“value”作为出现次数的 HashMap。 每当您阅读一个单词时,请检查该单词是否在地图中可用并增加其值。 如果您需要代码示例,请告诉我们。

如果我是你,我会在一个string读取一次输入的所有文本,然后使用方法string.split(" ");

这将返回一个包含输入中所有单词的string数组。 然后对 Array 执行循环并在输入中计算您团队的结果。

如果您在编写代码方面需要进一步帮助,请随时询问

暂无
暂无

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

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