0

我写了一个方法,每次看到一个新单词时都会给int被调用者加 1:total

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

4 回答 4

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;
}
于 2013-01-02T03:08:19.740 回答
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;

}

否则循环将无限运行。

于 2013-01-02T03:11:14.367 回答
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();
  }
}
于 2013-01-02T03:22:09.257 回答
0

正如其他人所说,您有一个无限循环。还有一种更简单的使用扫描仪的方法。

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

    while(s.hasNext()){
        s.next();
        total++;
    }
    return total;
于 2013-01-02T03:31:10.107 回答