Jeremy Fisher
Jeremy Fisher

Reputation: 2782

Infinite loop while using Scanner to read file Java

So I am trying to parse text files that could be in the form

words words words werdz words

or

words
words
words
words
words

Because of this, I decided to use Scanner instead of BufferedReader, and I'm not very experienced with using Scanner. I am trying to read a file and save to a Collection. Here is the main code and the supplementary methods.

main:

public static void main(String[] args) throws IOException {

        LinkedList<String> unmodDict = readDict(new File(args[0]));
        String[] unsorted = readUnsorted(new File(args[1]));

        ...

} 

readDict()

public static LinkedList<String> readDict(File file) throws IOException {
        //BufferedReader reader = new BufferedReader(new FileReader(file));
        Scanner s = new Scanner(new FileReader(file));
        String line = null;
        LinkedList<String> ll = new LinkedList<>();
        int count = 0;
        while(s.hasNext()) {
            ll.add(s.next());
        }
        // this loop seems to run finitely.
        s.close();
        return ll;
    }

readUnsorted()

public static String[] readUnsorted(File file) throws IOException {
        //BufferedReader reader = new BufferedReader(new FileReader(file));
        Scanner reader = new Scanner(new FileReader(file));
        int count = 0;
        while (reader.hasNext()) {
            count++;
        }
        reader.close();
        // The above loop is running infinitely.

        Scanner reader2 = new Scanner(new FileReader(file));
        String line2 = null;
        String[] unsortedWerdz = new String[count];
        int i = 0;
        while (reader2.hasNext()) {
            unsortedWerdz[i] = reader2.next();
            i++;
        }
        reader2.close();

        return unsortedWerdz;
    }

For some reason, the first while loop in the readUnsorted method is running infinitely but I can't see why since the first loop in the readDict method seems to run fine. Could someone advise me on what to do?

Thanks

Upvotes: 1

Views: 1732

Answers (1)

Zhedar
Zhedar

Reputation: 3510

It run's forever, since you check if there's a next String avaiable, but you don't retrieve it! You need to get it via next() like this:

while (reader.hasNext()) {
            reader.next();
            count++;
        }

Otherwise the Scanner will always point at the same (the first) element it reads and always report: Yes, there's another token in here!

Upvotes: 1

Related Questions