简体   繁体   English

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

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

I have been asked to write a program that checks if the team name is present in the text file I had created on my computer and also say how many times it has been repeated on the file?我被要求编写一个程序来检查我在计算机上创建的文本文件中是否存在团队名称,并说明它在文件中重复了多少次? Can you please help me out?你能帮我一下吗? I have written the code to check if the word is present but did not know how to check the number of times it is present.我已经编写了代码来检查这个词是否存在,但不知道如何检查它出现的次数。

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

    }
}

Basically you can reuse your already existing for loop基本上你可以重用你已经存在的for循环

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

Introduce a variable counter that is initialized as 0 and incremented if the team name matches.引入一个变量counter ,该counter初始化为 0,如果团队名称匹配则递增。

Additionally I suggest to re-structure your code.此外,我建议重新构建您的代码。

  1. Read the content of the file in separate method.以单独的方法读取文件的内容。 Let the method return a String[] that is stored to String[] winners .让该方法返回一个String[]存储到String[] winners
  2. Ask the user for the team name.向用户询问团队名称。
  3. Check whether the array winners contains the team name.检查数组winners是否包含团队名称。 This happens already in your method checkSeries() .这已经发生在您的方法checkSeries() As you can imagine from my previous comments, I would move the Scanner code to the method described in 1. Remember that a methods name should describe what's happening in the method - so checkSeries() should only check and return a yes or no.正如您可以从我之前的评论中想象的那样,我会将 Scanner 代码移动到 1 中描述的方法。请记住,方法名称应该描述方法中发生的事情 - 因此checkSeries()应该只检查并返回是或否。
  4. Reuse the for-loop of checkSeries() in a new method that counts.在计数的新方法中重用checkSeries()的 for 循环。 This method needs only to be called if checkSeries() returned true.仅当checkSeries()返回 true 时才需要调用此方法。

Instead of result = true;而不是result = true; you could just increment a counter inside your loop.你可以在循环内增加一个计数器。

For example:例如:

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

And you could then change the return type of your method to int and return counter .然后您可以将方法的返回类型更改为int并返回counter

A method that just returns true / false could use the new method.只返回 true / false 的方法可以使用新方法。 If the returned value is 0, it returns false, else true.如果返回值为 0,则返回 false,否则返回 true。

You could use a HashMap with "key" as the word and "value" as the number of occurrences.您可以使用以“key”作为单词和“value”作为出现次数的 HashMap。 Whenever you read a word check whether the word is available in the map and increment its value.每当您阅读一个单词时,请检查该单词是否在地图中可用并增加其值。 Let know if you need a code example.如果您需要代码示例,请告诉我们。

If I were you, I would read all the text input once in a string then split it with the in between white spaces using the method string.split(" ");如果我是你,我会在一个string读取一次输入的所有文本,然后使用方法string.split(" ");

This will return an Array of string that contain all the words in your input.这将返回一个包含输入中所有单词的string数组。 Then perform a loop on the Array and count the result of your team in the input.然后对 Array 执行循环并在输入中计算您团队的结果。

If you want further help in writing the code, feel free to ask如果您在编写代码方面需要进一步帮助,请随时询问

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

相关问题 如何计算Java中文本文件中单词出现的次数? - How to count the amount of times a word shows up in text file in Java? 如何计算单词出现在数组中的次数 - How to count the number of times a word appears in an array 如何计算数字出现在.txt文件中的次数 - How to count how many times a number appears in a .txt file 如何统计txt文件中特定单词出现的行数? - How to count the number of lines that a specific word occurs in a txt file? 该方法应该计算“.”、“?”或“!”的次数。 出现在文中 - the method is supposed to count the number of times a ‘.’, ‘?’, or ‘!” appears in the text 计算一个单词输入次数的程序,然后按降序返回单词和使用次数 - Program to count the number of times a word is entered then return the word and number of times used in descending order 如何将文本文件读取到数组中,计算出现的次数,然后显示计数 - How to read a text file into an array, count the number of occurrences and then display the count HashMap字符串和计数每个单词的使用次数 - HashMap String and Count number of times each word is used 有没有一种方法可以计算单词在字符串中重复的次数? - Is there a way to count the number of times a word has repeated in a string? 获取单词在文本文件中出现的次数,并将其链接到文本文件 - Get how many times a word appears in a text file and link it to a text file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM