Home > Net >  Preventing a never ending while loop in Java
Preventing a never ending while loop in Java

Time:04-13

I have the following code which checks a file being imported and I want to count the number of lines of data it has so I can assign them to an array. But the loop just keeps running and does not stop at the 8 lines of data I have.

This is the code I have for the count that keeps looping:

Scanner in = new Scanner (new FileInputStream("src/data/VinylRecords.txt"));
int lines = 0;
while (in.hasNextLine()) {
    lines  = 1;
}
System.out.println("number of lines "   lines);

I am very new to Java but have used while loops before ok and cannot see what is wrong with this? Please can anyone help point me in the right direction?

CodePudding user response:

"The hasNextLine() is a method of Java Scanner class which is used to check if there is another line in the input of this scanner. It returns true if it finds another line, otherwise returns false" https://www.javatpoint.com/post/java-scanner-hasnextline-method but it does not change the scanner value. you need to add .nextLine()

  • Related