该程序旨在告诉我文件中有多少单词,但它给了我很高的数字。暗示它正在读取字符数而不是单词,或者是单独的逻辑错误。
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 "";
}
}
答案 0 :(得分:4)
words.split("\\s+");
不会修改words
;它只返回一个新数组。您忽略了返回值并在原始字符串上调用length()
。将其更改为:
return words.split("\\s+").length;
答案 1 :(得分:2)
string.split()
返回一个字符串数组(http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-)
public int wordCount() {
String str = readFile();
System.out.println(str);
String[] words = str.split("\\s+");
return words.length;
}