Getting infinite loop when reading file from method

tavalendo :

I am trying to refactor my code, and adding methods where possible. When I read a file from a method and return the result of the computation, the code goes into extreme memory consumption, infinite loop.

My modification looks like this:

import java.util.Scanner;

public class NumberOfLines {
    public static int compute () {
        // read this file
        String theFile = "numbers.txt";

        Scanner fileRead = null;

        if (NumberOfLines.class.getResourceAsStream(theFile) != null) {
            fileRead = new Scanner(NumberOfLines.class.getResourceAsStream(theFile));
        }           
        else {
            System.out.print("The file " + theFile + " was not found");
            System.exit(0);
        }

        System.out.println("Checkpoint: I am stuck here");

        // count number of lines
        int totalLines = 0;
        while(fileRead.hasNextInt()) {
            totalLines++;

        }
        fileRead.close();
        return totalLines;

    }

    public static void main (String[] args) {

        System.out.println("The total number of lines is: " + compute());


    }
}

If instead of writing the method, and placing the code on main, then it works. Why is this?

EDIT

Contents of numbers.txt is:

5 
2
7
4
9
1
5
9
69
5
2
5
6
10
23
5
36
5
2
8
9
6

So I expect out put to be:

The total number of lines is: 22

Nicholas K :

The reason you are getting stuck in an infinite loop is because you are reading the file but not incrementing the scanners token in the while loop. So the while condition is always true.

while (fileRead.hasNextInt()) {
    totalLines++;
    fileRead.nextInt();  // change made here only
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127993&siteId=1