【问题标题】:How to call a void method in the main? [duplicate]如何在 main 中调用 void 方法? [复制]
【发布时间】:2018-05-15 12:26:28
【问题描述】:
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");}

如何在main方法中调用这个方法

【问题讨论】:

  • 由于这不是静态的,您首先需要实例化该方法所属的任何类。
  • 你已经在使用这个例子了。 println 是一个实例 void 方法,它接受一个参数。你是怎么打电话给println的? ...通过使用实例System.out
  • 顺便说一句,最简单的解决方案是将此方法设为static,因为它不必是实例方法。同样,您的 mainstatic 方法,因此您已经知道如何执行此操作。

标签: java methods void


【解决方案1】:

Main 方法是静态的,从静态方法中您只能调用静态方法。 你可以做的是:

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);
    }
}

【讨论】:

  • 可以,但是由于 amPm 方法只使用了参数,所以你可以将其标记为静态。
  • 我不能改代码,这是作业XD
  • 哪里不能改?
  • 在哪里?我不明白
  • 你指的是哪些变化?只要它是 homework XD 就不能正常工作(我假设你的意思是:(time &gt;= 0 &amp;&amp; time &lt; 12) change。在你的代码中,你的方法不可能打印“AM”,因为你想要同时输入 >=12 和
【解决方案2】:

您需要创建A 类的对象实例,因为此方法不是静态的。然后您可以在该引用上调用该方法:

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 */
}    

【讨论】:

  • 你能解释一下我听不懂吗:(
【解决方案3】:

您的方法不是静态的,因此您应该从该方法所属的类创建对象。 这个想法是: 静态方法是类级别的,所以不能从静态方法调用非静态方法。

【讨论】:

    猜你喜欢
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    相关资源
    最近更新 更多