【问题标题】:No output while using static methods inside a class(the class which has no main function in it)在类中使用静态方法时没有输出(其中没有主函数的类)
【发布时间】:2020-12-12 03:38:56
【问题描述】:

这是我的主要课程:

public class App {
    public static void main(String[] args){
        Student s1=new Student();
        
    };
    };

这是创建的类:

class Student {
    public static void f1(){
        f2();
    }
    public static String f2(){
        
        return "hello";
    }
    public Student(){
        f1();
    }

}

现在,因为我在主类中创建了一个对象 s1,所以调用了构造函数,它有 f1(),所以 f1() 被调用,现在 f1() 有 f2(),所以 f2() 被调用,所以我认为必须打印“你好”,但根本不打印输出(什么都不打印)。谁能解释一下可能是什么原因?

【问题讨论】:

  • 这里没有任何东西可以打印任何东西。你的期望是没有根据的。

标签: java function class methods


【解决方案1】:

打印和返回值是有区别的。 如果你想让它被打印出来,你应该尝试做这样的事情:

class Student {
    public static void f1(){
        f2();
    }
    public static void f2(){
        
        System.out.print("hello");
    }
    public Student(){
        f1();
    }

}

【讨论】:

    【解决方案2】:

    f2() 正在返回 String,但 f1 没有打印它:

    public static void f1(){
        System.out.println(f2());
    }
    public static String f2(){    
        return "hello";
    }
    public Student(){
        f1();
    }
    

    【讨论】:

      【解决方案3】:

      要在控制台日志中打印,您应该尝试:System.out.println("Hello");

      您正在返回值而不是打印它。

      【讨论】:

        【解决方案4】:

        你必须使用 System.out.println("Hello") 而不是 return "hello";

        【讨论】:

          【解决方案5】:

          我的方法....

          由于f2方法有返回类型,为了得到从中得到的值,对与返回类型兼容的类型做一个引用,用下面相同的引用代码写出hello这个词

          class Student {
          public static void f1(){
              String x=f2(); //method calling
              System.out.println(x);
          
          }
          public static String f2(){
              
              return "hello";
          }
          public Student(){
              f1();
          }
          

          }

          二法……

          你可以试试这个方法……

          class Student {
          public static void f1(){
              
              System.out.println(f2());//calling method
          
          }
          public static String f2(){
              
              return "hello";
          }
          public Student(){
              f1();
          }}
          

          【讨论】:

            猜你喜欢
            • 2013-11-28
            • 1970-01-01
            • 1970-01-01
            • 2022-10-24
            • 1970-01-01
            • 1970-01-01
            • 2021-01-28
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多