0
public void AmPm(int time) {
 if (time >= 12 && time < 12)
   System.out.println("AM");
 else if (time >= 12 && time < 24)
   System.out.println("PM");
 else
   System.out.println("invalid input");}

How can I call this method in the main method

xxxvodnikxxx
  • 1,270
  • 2
  • 18
  • 37
Atheer
  • 11
  • 1
  • 1
  • 4
  • 6
    Since this isn't static, you would first need to instantiate whatever class this method belongs to. – khelwood Dec 01 '17 at 11:46
  • 1
    You already are using example of this. `println` is an instance `void` method which takes one argument. How did you call `println`? ... by using the instance `System.out` – Peter Lawrey Dec 01 '17 at 11:56
  • 1
    BTW the simplest solution is to make this method `static` as it doesn't have to be an instance method. Again, your `main` is a `static` method so you know how to do this already. – Peter Lawrey Dec 01 '17 at 11:57

3 Answers3

1

Main method is static, and from static methods you can call only static ones. What you can do is:

class A {
    public void amPm(int time) {
       if (time >= 0 && time < 12) //you have a typo there
           System.out.println("AM");
       else if (time >= 12 && time <24)
           System.out.println("PM");
       else
           System.out.println("invalid input");
    }
    //or as static method:
    public static void amPmInStaticWay(int time) { //... }

    public static void main(String[] args) {
        //...
        A a = new A();
        a.amPm(time);
        //or
        amPmInStaticWay(time);
        //or if you want to use static method from different class
        A.amPmInStaticWay(time);
    }
}
Dawid Fieluba
  • 1,271
  • 14
  • 34
1

You need to create an instance of object of class A because this method isn't static. Then you can call that method on that reference:

public static void main(String[] args) {
    A a = new A();
    a.amPm(time); /* instead of typing "time" you need to pass int value that you want to be passed to the method as an argument */
}    
Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21
0

your method not static so you should create object from the class this method belongs to. The idea is : The static methods is at class level, so you can't call non static methods from static methods.