简体   繁体   中英

Reading from a txt file

I wrote a method that adds 1 to an int called total each time it sees a new word:

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

Is that the right way to write it?

It looks fine. But the inner IF is unnecessary, also the next() method is required. Below should be fine.

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

The Scanner implements Iterator.You should at least make the iterator step forward, like this:

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;

}

or the loop will run infinitely.

Use a regular expression to match all non-whitespace. :-)

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

As others have said you have an infinite loop. Also there is a much simpler way to use Scanner.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM