Search code examples
javamethodsundefined

java calling method fails as method undefined


I have a method written which checks a specific file to count how many lines it has:

public int countFileRecords() 

        {
        Scanner in = new Scanner (new FileInputStream("src/data/VinylRecords.txt"));
        int lines = -1;
        while (in.hasNextLine()) //loop while there is a new line
        {lines +=1; // add one to my counter
        in.nextLine();} // move to the next line and loop again
        return lines;
        }

but when I try and call this from another class I get an error "the method is undefined for the type"

public class Test 
{
    public static void main(String[] args)
{
System.out.println(countFileRecords());
}

I am still learning java and I think I need to do something to tell this class what to call.

I want to be able to call and run the method to check the current number of lines int he files - But I thought all the information was in the method so this should work. I would like to understand why it does not so I can correct it. Thanks.


Solution

  • public class Test 
    {
        public static void main(String[] args)
    {
    System.out.println(countFileRecords());
    }
    

    Calling the method like that (using just the name of the method to call it) will not compile , you can inside a static method call another static method in the same class , or an imported static method declared in another class.

    So you should make the countFileRecords method static in the declaration ( adding static keyword) and then import using import static to can call it directly using the just the method name :


    package com;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class Main {
        public static int countFileRecords() 
        {
            Scanner in=null;
            try {
                in = new Scanner(new FileInputStream("src/data/VinylRecords.txt"));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int lines = -1;
            while (in.hasNextLine()) // loop while there is a new line
            {
                lines += 1; // add one to my counter
                in.nextLine();
            } // move to the next line and loop again
            return lines;
        }
    }
    

    package com;
    
    import static com.Main.countFileRecords;
    
    public class Test {
        public static void main(String[] args) {
            System.out.println(countFileRecords());
        }
    }