Raj*_*wal -1 java arrays methods
我在编译这个程序时遇到错误:
class ArraysInMethods {
public static void main(String[] args) {
int array[]={1,6,2,5,3,8,9,0,5};
Add5(array);
for(int y : array){
System.out.println(y);
}
}
public void Add5(int x[]){
for(int counter=0; counter < x.length; counter++){
x[counter]+=5;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static method Add5(int[]) from the type ArraysInMethods
at ArraysInMethods.main(ArraysInMethods.java:6)
Run Code Online (Sandbox Code Playgroud)
你去,让你的Add5方法静态:
public static void Add5(int x[]){
for(int counter=0; counter < x.length; counter++){
x[counter]+=5;
}
}
Run Code Online (Sandbox Code Playgroud)
基本上它意味着只能从静态方法中调用静态方法,main而Java中的方法是静态的.
编辑:你为什么要那样做?因为类的静态成员不存在类的实例,非静态成员是否存在.如果你在没有创建一个试图调用非静态方法的类(有效)的实例的情况下调用静态方法,那么它将无法工作,因为没有类的实例就不存在非静态方法.
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |