[英]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.