0

Im a first year CS student and I am working on an assignment but I ran into this while loop that won't stop...

import java.io.*;
import java.util.Scanner;

class Ass1{
public static void main(String[] args){
    int i=0;

    try{
        File myfile = new File ("./ages.txt");
        Scanner scanner = new Scanner(myfile);

        while(scanner.hasNext()){
            i++;
        }
        System.out.println("ages.txt contains " + i + " lines");
        scanner.close();
    }catch(IOException e){}
}
}

and the ages.txt file looks like the following (They are meant to be all in separate lines but somehow I can only show them in a line here :( )

200 201 202 203 205 205 207 208 210 213 214 217 218 219 219 221 225 226 227 227 231 232 238 238 240 309 313 314

I am trying to read all the lines from the text file and at the end print how many lines it contains.

Thank you in advance for your help.

1
  • 4
    You never advance the cursor. And you'll want to use hasNextLine(). Commented Oct 17, 2013 at 21:11

2 Answers 2

4

You need to advance your scanner by calling scanner.next();

If you were counting lines, it would be better to use scanner.hasNextLine() and scanner.nextLine() respectively.

The way you have it written, scanner.hastNext() will always evaluate to true as the scanner has never actually left it's initial position, so there will always be a hasNext()

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for quick reply. but how would I go about adding scanner.next(); ?
NP, good luck in your studies. And you can add it by typing it :p. Just think where you would want to advance where your scanner was pointing. HINT: Think of where you are counting the lines.
@redFIVE +1 for not spoon feeding the OP
0

That's because you are not calling nextInt() method inside the while loop which means the Scanner never advances to the next token.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.