从txt文件中读取

时间:2013-01-02 03:04:24

标签: java

我写了一个方法,每次看到一个新单词时,int都会total添加1:

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;
}

这是写它的正确方法吗?

4 个答案:

答案 0 :(得分:5)

看起来很好。但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;
}

答案 1 :(得分:2)

Scanner实现了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;

}

或循环将无限运行。

答案 2 :(得分:0)

使用正则表达式匹配所有非空格。 : - )

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();
  }
}

答案 3 :(得分:0)

正如其他人所说,你有一个无限循环。还有一种更简单的方法来使用Scanner。

    int total = 0;
    Scanner s = new Scanner(new File("/usr/share/dict/words"));

    while(s.hasNext()){
        s.next();
        total++;
    }
    return total;