-2

I want to use "public int CountWord" instead of "public static int CountWord", below code its give me error that, Cannot make a static reference to the non-static method CountWord(String, String) from the type CountWord , why i am getting this error and how can i use it without using static keyword. Thanks

public static void main(String[] args) {
    System.out.println(CountWord("the","test.txt"));
}

public int CountWord(String word, String textFilePath){

}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
M.J.Watson
  • 470
  • 7
  • 18
  • 3
    I strongly suggest you read the Java tutorials (https://docs.oracle.com/javase/tutorial/), this is a very basic language mechanic, and shouldn't really be asked about here. – Socratic Phoenix Mar 05 '16 at 11:53

3 Answers3

2

Try to create an instance of class to invoke the method like this:

   public static void main(String[] args) {
        ClassName cn = new ClassName();
        System.out.println(cn.CountWord("the","test.txt"));
    }

    public int CountWord(String word, String textFilePath){

    }
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
2

bcoz CountWord() is an instead method , to access it within main()(a static method ) you'll need an instance of the class of CountWord()

for ex:

class Test{

     public static void main(String[] args) {
            Test t = new Test();
            System.out.println(t.CountWord("the","test.txt"));
        }
     public int CountWord(String word, String textFilePath){
        }
}
Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
1

static means that the method belongs to an object. In order to use this method you must first create an object of the class declaring the method.

Suppose your class looks like this:

public class WordCounter{
    public int countWord(String word, String textFilePath){
         ....
    }
}

Then your main method would look like this:

    public static void main(String[] args){
         WordCounter counter = new WordCounter();
         counter.countWord("I am a String", "I am too");
    }
masinger
  • 775
  • 6
  • 13