调用静态方法

时间:2012-02-02 11:36:17

标签: java static-methods

这段代码如何显示编译error-void是变量测试的无效类型

public class Tester{
        public static void main(String[] args){
           static void test(String str){
         if (str == null | str.length() == 0) {
            System.out.println("String is empty");
         } 
         else {
            System.out.println("String is not empty");
         }}
       test(null);   

5 个答案:

答案 0 :(得分:4)

您尝试在另一个方法(test)中声明一个方法(main)。不要那样做。将test()直接移到课堂中:

public class Tester{
  public static void main(String[] args) {
    test(null); 
  }

  static void test(String str) {
    if (str == null | str.length() == 0) {
      System.out.println("String is empty");
    } else {
      System.out.println("String is not empty");
    }
  }
}

(请注意,我还修复了缩进和空格。您可以使用各种约定,但是您应该比问题中的代码更一致且更清晰。)

答案 1 :(得分:0)

您无法在其他方法中声明方法。从test推迟main。而你也无法从课堂上调用方法。 test(null);必须在方法内,例如main。

public class Tester{
        public static void main(String[] args){
            test(null);
        }

        static void test(String str){
         if (str == null | str.length() == 0) {
            System.out.println("String is empty");
         } 
         else {
            System.out.println("String is not empty");
         }
        }

答案 2 :(得分:0)

您的方法测试在另一种方法中。

只需将测试方法放在主体之外。

答案 3 :(得分:0)

public class Tester{

    public static void test(String str){
        if (str == null || str.length() == 0) {
            System.out.println("String is empty");
        }
        else {
            System.out.println("String is not empty");
        }
    }

    public static void main(String[] args){
        test(null);
    }

}

您还必须添加双精度数或操作数(||)才能在没有空指针异常错误的情况下正常工作。

答案 4 :(得分:0)

您在main方法中声明测试方法。因此,将测试方法与main分开。

public class Tester
{
    public static void test(String str)
    {
        if (str == null || str.length() == 0)
        {
            System.out.println("String is empty");
        }
        else
        {
            System.out.println("String is not empty");
        }
    }

    public static void main(String[] args)
    {
        test(null);
    }
}
相关问题