Question

So i'm writing a program that fills a partially filled array from data from a file and I need to know the amount of lines in the file so I can make that a condition on my for loop so there isn't a bounds exception. So I have created a method that says:

public static int lineFinder(String[] names) throws FileNotFoundException
    {
        Scanner in = new Scanner(new File("prog6_1.txt"));
        int count = 0;

        while(in.hasNextLine())
        {
           count++;
        }
        return count;
         }

My file looks like this:

3459 Kait Elizabeth Brown 4.00

5623 Rachel Jessica Smith 3.45

9837 Thomas Robert Doe 3.73

1235 Riley Leigh Green 2.43

And it never terminates and I can't figure out why since I put an extra line at the end. Any suggestions?

Was it helpful?

Solution 2

hasNextLine() only checks, but doesn't consume the line. You need to call nextLine() inside the loop.

OTHER TIPS

The hasNextLine() method doesn't move the cursor ahead. You need to do that by using nextLine() method inside the loop.

hasNextLine() just checks if the next line is available it does not fetch the next line, for that you should make use of nextLine() after you have verified that the next line is present. Modify your while loop as follows :

 while(in.hasNextLine())
    {
      in.nextLine();
       count++;
    }

The hasNextLine() does not advance the cursor (ie, it doesn't consume the line). Your code should use in.nextLine() and look like this:

public static int lineFinder(String[] names) throws FileNotFoundException
{
    Scanner in = new Scanner(new File("prog6_1.txt"));
    int count = 0;

    while(in.hasNextLine())
    {
        in.nextLine();
        count++;
    }
    return count;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top