所以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));
}
}
}
还有另一种可能的解决方案,将嵌套的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方法起作用。
您不能在非静态类中访问静态方法。有两种可能的解决方案:-1.将解决方案设为静态
public static class Solution {
public static void main(String[] args) {
//...
}
}
-2.从主方法中删除静电
public class Solution {
public void main(String[] args) {
//...
}
}
有两种可能的解决方案(两种都可行):
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
或顶级类型内。