Search code examples
javafileclassmethodscall

How to call a method from another class, which is in another .java file?


The teacher gave us a .java file in which there is a method that I need to use in order to solve my question.

Here's the question : Call the method countEnglishWords() given in the file SentenceChecker. This method takes as input a String and outputs the number of English words it contains.

My problem is that I do not know how to call a method which is in another class which is in another .java file!


Solution

  • you must ensure that the class & method you're trying to call have appropriate access modifiers (e.g. public). Then from your class' file, you may import the SentenceChecker class at the top.

    String str = "Lorem ipsum dolor sit amet your mom";
    SentenceChecker sc = new SentenceChecker();
    sc.countEnglishWords(str); // this will call, you could assign any ret result to variable
    

    edit: you don't necessarily need import statement (i.e. files are in same dir).

    1. Put your sentence checker in some empty dir, say "/CheckerProgram"
    2. Create MySentenceCheckerCaller.java in same directory
    3. Edit MySentenceCheckerCaller.java to:

      public class MySentenceCheckerCaller {
        public static void main(String[] args) {
           String str = "Lorem ipsum dolor sit amet your mom";
           SentenceChecker sc = new SentenceChecker();
           int wordCount = sc.countEnglishWords(str); // call method, assumes returns an int
           System.out.println("There are " + wordCount + " words in my string.");
         }
       }
      
    4. Compile MySentenceCheckerCaller.java and SentenceChecker.java
    5. Ensure that you have MySentenceCheckerCaller.class and SentenceChecker.class in program directory
    6. Run java MySentenceCheckerCaller in terminal