查找指定文本文件中的单词数的Java程序

1 说明

在此程序中,我们需要找到给定文本文件中出现次数最多的单词。这可以通过使用文件指针以读取模式打开文件来完成。逐行读取文件。一次分割一行并存储在数组中。遍历数组并计数单词。该程序中使用的data.txt文件的内容如下所示。

data.txt内容如下:

A computer program is a collection of instructions that performs specific task when executed by a computer.
Computer requires programs to function.

Computer program is usually written by a computer programmer in programming language.

A collection of computer programs, libraries, and related data are referred to as software.

Computer programs may be categorized along functional lines, such as application software and system software.

2 算法思路

  • 步骤1:开始
  • 第2步:定义字符串行
  • 步骤3:SET count =0
  • 步骤4:使用File Reader以读取模式打开文件。
  • 步骤5:从文件中读取行
  • 步骤6:重复步骤7至步骤8,直到到达文件末尾
  • 第7步:将行拆分为单词,然后将其存储在数组字符串word []中。
  • 步骤8: count = count + words.length
  • 步骤9:打印count。
  • 步骤10:结束

3 程序实现

/**
 * 一点教程网: http://www.yiidian.com
 */
import java.io.BufferedReader;  
import java.io.FileReader;  
  
public class CountWordFile  
{  
    public static void main(String[] args) throws Exception {  
        String line;  
        int count = 0;  
  
        //Opens a file in read mode  
        FileReader file = new FileReader("data.txt ");  
        BufferedReader br = new BufferedReader(file);  
  
        //Gets each line till end of file is reached  
        while((line = br.readLine()) != null) {  
            //Splits each line into words  
            String words[] = line.split("");  
            //Counts each word  
            count = count + words.length;  
  
        }  
  
        System.out.println("Number of words present in given file: " + count);  
        br.close();  
    }  
}  

以上代码输出结果为:

Number of words present in given file: 63

 

热门文章

优秀文章