1

Why does my loop run to infinity instead of stopping at some point even though when there is finite(10) number of lines in my text file.

import java.util.*;
import java.io.*;
public class numberOfLines{
    public static void main(String[] args){
       try{
          Scanner cs=new Scanner(new File("poem.txt"));
          int i=0;
          while(cs.hasNextLine()){
             System.out.println(i);
           }
        } catch(FileNotFoundException e){
          System.out.print("File not found");
          } 
    }
}

Thanks in advance for your help on this problem.

Jason
  • 11,744
  • 3
  • 42
  • 46
jason
  • 45
  • 6
  • 4
    You never actually read the next line, so the `Scanner` stays on line 0 and returns `true`. – Zircon Nov 30 '16 at 20:43
  • By the way, this is how you count the [number of lines in a file](http://stackoverflow.com/questions/453018/number-of-lines-in-a-file-in-java) – OneCricketeer Nov 30 '16 at 20:45
  • If you never move forward, the answer to *"Are we there yet?"* will never change. – Andreas Nov 30 '16 at 20:57

2 Answers2

2

Because you never call cs.nextLine(). That means you never consume the value which is in the Scanner. So ca.hasNextLine() ever return true;

Jens
  • 67,715
  • 15
  • 98
  • 113
1

You need to use something like cs.nextLine() to actually read a line, otherwise there's always a line left since you are never advancing through the file contents.

TWA
  • 12,756
  • 13
  • 56
  • 92