【发布时间】:2017-08-27 19:59:21
【问题描述】:
该程序旨在告诉我文件中有多少个单词,但它给了我非常高的数字。暗示它读取的是字符数而不是单词数,或者是单独的逻辑错误。
package wordinspection;
import java.io.*;
import java.util.*;
public class WordInspection {
private Scanner reader;
private File file;
public WordInspection(File file) {
this.file = file;
}
public int wordCount() {
String words = readFile();
System.out.println(words);
words.split("\\s+");
return words.length();
}
public String readFile() {
try {
String str = "";
Scanner reader = new Scanner(file, "UTf-8");
while (reader.hasNextLine()) {
str += reader.nextLine();
str += "\n";
}
return str;
} catch (FileNotFoundException e) {
System.out.println("Does nothing");
return "";
}
}
【问题讨论】:
-
我有文件,是普通的文本文件。