[英]Reading from a txt file
我寫了一個方法,每次看到一個新單詞,就將1加到一個稱為total
的int
:
public int GetTotal() throws FileNotFoundException{
int total = 0;
Scanner s = new Scanner(new BufferedReader(new FileReader("Particles/Names.txt")));
while(s.hasNext()){
if(s.hasNext()){
total++;
}
}
return total;
}
那是寫的正確方法嗎?
看起來不錯。 但是inner IF
是不必要的,也需要next()
方法。 下面應該沒問題。
public int GetTotal() throws FileNotFoundException{
int total = 0;
Scanner s = new Scanner(new BufferedReader(new FileReader("Particles/Names.txt")));
while(s.hasNext()){
s.next();
total++;
}
return total;
}
掃描器實現了Iterator。您至少應使迭代器向前邁進,如下所示:
public int GetTotal() throws FileNotFoundException{
int total = 0;
Scanner s = new Scanner(new BufferedReader(new FileReader("Particles/Names.txt")));
while(s.hasNext()){
s.next();
total++;
}
return total;
}
否則循環將無限運行。
使用正則表達式匹配所有非空格。 :-)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScanWords {
public ScanWords() throws FileNotFoundException {
Scanner scan = new Scanner(new File("path/to/file.txt"));
int wordCount = 0;
while (scan.hasNext("\\S+")) {
scan.next();
wordCount++;
}
System.out.printf("Word Count: %d", wordCount);
}
public static void main(String[] args) throws Exception {
new ScanWords();
}
}
正如其他人所說,您有一個無限循環。 還有一種使用掃描儀的簡單得多的方法。
int total = 0;
Scanner s = new Scanner(new File("/usr/share/dict/words"));
while(s.hasNext()){
s.next();
total++;
}
return total;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.