Java 计算返回的字符数中的单词数,而不是单词数
这个程序的目的是告诉我一个文件中有多少个单词,但它给了我很多数字。这意味着它读取的是字符数而不是单词数,或者是一个单独的逻辑错误Java 计算返回的字符数中的单词数,而不是单词数,java,string,file,Java,String,File,这个程序的目的是告诉我一个文件中有多少个单词,但它给了我很多数字。这意味着它读取的是字符数而不是单词数,或者是一个单独的逻辑错误 package wordinspection; import java.io.*; import java.util.*; public class WordInspection { private Scanner reader; private File file; public WordInspection(File file) { this.fil
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 "";
}
}
words.split(\\s+)代码>不修改单词
;它只返回一个新数组。您将忽略返回值并对原始字符串调用length()
。将其更改为:
return words.split("\\s+").length;
words.split(\\s+)代码>不修改单词
;它只返回一个新数组。您将忽略返回值并对原始字符串调用length()
。将其更改为:
return words.split("\\s+").length;
string.split()
返回字符串数组()
string.split()
返回字符串数组()
我有这个文件,它是一个普通的文本文件。我有这个文件,它是一个普通的文本文件。