我正在編寫一個程序,它將掃描一個文本文件並計算其中的單詞數。對於賦值的單詞的定義是:'一個單詞是隻包含字母(a,...,z,A,...,Z)的非空字符串,由空格,標點符號,連字符組成的包圍 ,行開始或行結束。 '。從Java中的文本文件中計數單詞
我在java編程方面很新手,到目前爲止我已經設法編寫了這個實例方法,據推測這應該可行。但事實並非如此。
public int wordCount() {
int countWord = 0;
String line = "";
try {
File file = new File("testtext01.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
line = line + input.next()+" ";
input.next();
}
input.close();
String[] tokens = line.split("[^a-zA-Z]+");
for (int i=0; i<tokens.length; i++){
countWord++;
}
return countWord;
} catch (Exception ex) {
ex.printStackTrace();
}
return -1;
}
什麼是輸入文件的樣子,和你做什麼輸出到目前爲止? – Ash
此代碼:for(int i = 0; i
ControlAltDel
輸入文件看起來像這樣。其記事本: 這是第1行。 這是另一行,第2行。 正在下雨,拿傘。 正在下雨。拿傘!真。 第五行很短。他說:「拿傘!」 另一行,行... 他有一個嗎?沒有。 爲什麼不呢? 輸出是目前: java.util.NoSuchElementException \t在java.util.Scanner.throwFor(未知來源) \t在java.util.Scanner.next(未知來源) \t在TextAnalysis16.wordCount(TextAnalysis16 .java:46) \t at TextAnalysis16.main(TextAnalysis16.java:32) 正文中的字數爲:-1 howto linebreak in comments? –