Home > front end >  Finding end of file in Java
Finding end of file in Java

Time:09-29

I have a method that loops through a file to find the number of lines.

static int findFileSize(Scanner f){
        System.out.println("Got to counter:");
        String str;
        int line_count = 0;
        while(f.hasNextLine()) {
            line_count  ;System.out.println(line_count);
            //str = f.nextLine();
        }System.out.println("File size: "   line_count);
        return line_count;
    }//end findFileSize 

When i don't include the str = f.nextLine();, i can see it indexing indefinitely. What causes this to happen? And is there a way of finding the number of lines in a .txt file without needing to unnecessarily store a data into a string?

CodePudding user response:

What causes this to happen?

You aren't reading anything from the Scanner, you're just asking it if you will be able to read something.

If you walk into a shop and ask if they have, say, carrots, if the answer is "yes", but you don't buy any carrots, the shop still has carrots. So, if you walk out and walk in to ask again, they will still have the carrots, so they will again answer "yes" (unless somebody else has bought them).

You have to "buy the carrots" by using f.nextLine().

without needing to unnecessarily store a data into a string?

You don't have to store it in a variable:

f.nextLine();

will read the String and immediately discard it. But there isn't really a huge difference between this and storing it in a variable: the variable only keeps the contents of the last-read line anyway. (But since you don't give str an initial value, it's not definitely assigned after the loop, so you can't read its value after the loop in any case).

  • Related