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

スキャナーはイテレーターを実装します。少なくとも、次のようにイテレーターを前進させる必要があります。

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 に答える