Reputation: 1261
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
Reputation: 159844
You need to consume the input from the Scanner
while (in.hasNext()){
in.next();
num++;
}
Upvotes: 7