Cristian Gutu
Cristian Gutu

Reputation: 1261

.hasNext() wont turn false

I have the following code and I cannot understand why .hasNext() wont turn false. I am reading from a file called test.

My code:

package printing;
import java.io.File;
import java.util.Scanner;

public class Printer {
    public int count() throws Exception{
        int num = 0;
        File f = new File("C:\\Users\\bob\\Desktop\\test.txt");
        Scanner in = new Scanner(f);
        while (in.hasNext()){
            num++;
        }
        return num;
    }
}

Main:

public class Main {
    public static void main(String[] args) throws Exception{
        Printer mine = new Printer();
        System.out.println(mine.count());
    }
}

File content:

4 4 6 3 8 8 8

What is wrong?

Upvotes: 0

Views: 113

Answers (2)

Reimeus
Reimeus

Reputation: 159844

You need to consume the input from the Scanner

while (in.hasNext()){
    in.next();
    num++;
}

Upvotes: 7

rgettman
rgettman

Reputation: 178303

You didn't consume any of the input. hasNext() doesn't consume any input.

The scanner does not advance past any input.

Add a call to next() inside the while loop to consume the input.

Upvotes: 1

Related Questions