为什么日食会在我编写公共静态无效值main(String [] args)

问题描述 投票:0回答:3

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

        }
    }
}
java eclipse methods static public
3个回答
1
投票

还有另一种可能的解决方案,将嵌套的Solution类从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方法起作用。


0
投票

您不能在非静态类中访问静态方法。有两种可能的解决方案:-1.将解决方案设为静态

public static class Solution {

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

}

-2.从主方法中删除静电

public class Solution {

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

}

0
投票

有两种可能的解决方案(两种都可行):

A。Solution声明为static,即

public static class Solution

B。删除外部类声明public class HackerRank,使Solution成为顶级类型,即]]

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) { // Now this will work
        Solution s = new Solution();
        long[] ar = { 10000, 20000, 30000 };    
        System.out.println(s.aVeryBigSum(ar));      
    }
}

请注意,static方法只能在static或顶级类型内。

© www.soinside.com 2019 - 2024. All rights reserved.