我无法计算给定文本文件中的单词数量。每次输入文本文件名时,程序都会返回"找不到文件"。这是我到目前为止的代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Enter File name: ");
Scanner input=new Scanner (System.in);
String fileName= input.nextLine();
FileReader wordReader;
try {
wordReader=new FileReader(fileName);
BufferedReader reader=new BufferedReader(wordReader);
String cursor;
String content="";
int numberWords=0;
while((cursor=reader.readLine()) !=null) {
String []_words=cursor.split("");
for(String w: _words)
{
numberWords++;
}
}
System.out.println("Total words: "+ numberWords);
}catch (FileNotFoundException ex) {
System.out.println("File not found");
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
File file = new File("sample.txt");
try(Scanner sc = new Scanner(new FileInputStream(file))){
int count=0;
while(sc.hasNext()){
sc.next();
count++;
}
System.out.println("Number of words: " + count);
}
答案 1 :(得分:0)
你没有正确分裂。按" "
而不是""
String []_words=cursor.split(" "); //-------------> Add Space
这将为您提供单词而非单个字符。
此外,您可以打印_words.length
而不是不必要地循环。