包含try和catch以及static String ReadFile的英文文本单词统计的JAVA的代码怎么写
时间: 2023-06-05 16:07:40 浏览: 106
以下是一个包含try和catch以及static String ReadFile的JAVA代码,用于统计英文文本的单词数量:
```
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
public class WordCounter {
public static void main(String[] args) {
String fileName = "textFile.txt";
String text = ReadFile(fileName);
HashMap<String, Integer> wordMap = CountWords(text);
System.out.println("Total number of words: " + wordMap.size());
}
/*
* 读取文本文件并返回文本字符串
*/
public static String ReadFile(String fileName) {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
System.err.println("Exception caught: " + e.getMessage());
}
return sb.toString();
}
/*
* 统计文本中每个单词的数量并返回一个HashMap
*/
public static HashMap<String, Integer> CountWords(String text) {
HashMap<String, Integer> wordMap = new HashMap<>();
String[] words = text.split("\\s+");
for (String word : words) {
Integer count = wordMap.get(word);
if (count == null) {
count = 0;
}
wordMap.put(word, count + 1);
}
return wordMap;
}
}
```
阅读全文