例如,我正在尝试做这样的事情
public class Test {
public static void main(String args[]) {
int[] arr = new int[5];
arrPrint(arr);
}
public void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
我收到一条错误消息,告诉我无法从静态环境引用非静态变量。那么,如果这是真的,我将如何在 main 中使用非静态方法呢?
你不能。非静态方法是必须在 Test 类的实例上调用的方法;创建一个 Test 实例以在您的 main 方法中使用:
public class Test {
public static void main(String args[]) {
int[] arr = new int[5];
arr = new int[] { 1, 2, 3, 4, 5 };
Test test = new Test();
test.arrPrint(arr);
}
public void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)