【问题标题】:Why eclipse show me error in the line where i have written public static void main(String[] args)为什么 eclipse 在我写的行中显示错误 public static void main(String[] args)
【发布时间】:2020-07-17 12:53:45
【问题描述】:

那么为什么public static void main(String[] args) 我得到了一个错误。我该怎么做才能解决它?

package linkedList;

public class HackerRank {

    public class Solution {

        // Complete the aVeryBigSum function below.
        public long aVeryBigSum(long[] ar) {
            long a=0;
            for(int i=0;i<ar.length;i++){
                a=ar[i]+a;
            }

            return a;
        }


        public static void main(String[] args) { ///why this line is not correct 
            Solution s= new Solution();
            long[] ar= {10000,20000,30000};

            System.out.println(s.aVeryBigSum(ar));

        }
    }
}

【问题讨论】:

  • 错误是什么?
  • 您在主类HackerRank 中有一个内部类Solution。您的 main 方法在 Solution 内部 - 这是不允许的,内部类不能有静态方法。

标签: java eclipse methods static public


【解决方案1】:

还有另一种可能的解决方案,将嵌套的解决方案类从 HackerRank 类中取出,因为我看到你目前没有对它做任何事情。

public class Solution {

    // Complete the aVeryBigSum function below.
    public long aVeryBigSum(long[] ar) {
        long a = 0;
        for (int i = 0; i < ar.length; i++) {
            a = ar[i] + a;
        }
        return a;
    }

    public static void main(String[] args) { 
        Solution s = new Solution();
        long[] ar = { 10000, 20000, 30000 };

        System.out.println(s.aVeryBigSum(ar));
    }
}

这可确保您的静态 main 方法有效。

【讨论】:

    【解决方案2】:

    您不能访问非静态类中的静态方法。这个问题有两种可能的解决方案: - 1. 使解决方案静态

    public static class Solution {
    
        public static void main(String[] args) {
        //...
        }
    
    }
    

    - 2. 去除main方法中的静态

    public class Solution {
    
        public void main(String[] args) {
        //...
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-22
      • 2011-12-10
      • 2019-11-23
      • 2018-11-12
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      相关资源
      最近更新 更多