【问题标题】:calling a static method [closed]调用静态方法[关闭]
【发布时间】:2012-02-02 11:36:17
【问题描述】:

这段代码怎么会显示编译错误-void 是变量 test 的无效类型

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

【问题讨论】:

  • test 方法移出main 方法
  • 请勿将字符串与 == 进行比较,而应与 .equals() 进行比较。 Strings Re 对象,如果要比较对象的值就需要.equals(),否则就是比较引用。
  • 如果其中一个操作数为 null == 有效,您应该使用它,因为如果您的 str 为 null,str.equals(null) 将抛出 NullPointerException -1 进行注释

标签: java static-methods


【解决方案1】:

您试图在另一个方法 (main) 中声明一个方法 (test)。不要那样做。直接将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");
    }
  }
}

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

【讨论】:

  • 谢谢你,澄清概念和代码约定
【解决方案2】:

你不能在另一个方法中声明一个方法。从main 推迟test。而且你也不能从类中调用方法。 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");
         }
        }

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:
      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);
          }
      
      }
      

      您还必须添加双精度或操作数 (||) 才能正常工作而不会出现空指针异常错误。

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多