我一直在尝试像教程中所说的那样在 Java 中声明一个数组,但收到了一个错误。这是我的代码:
public class ArrayExample {
private static final int SIZE = 15;
/* this works */
int[] arrayOfInt = new int[SIZE];
/* but this doesn't work, says "cannot find symbol" */
int[] arrOfInt;
arrOfInt = new int[SIZE];
public static void main(String[] args) {
/* but here it works; why? what's the difference? */
int[] arrOfInt;
arrOfInt = new int[SIZE];
}
}
我在教程中找不到这种差异的解释。为什么第二个声明不起作用,但 main
方法中的第三个声明起作用?
最佳答案
您不能将赋值语句编写为类定义的一部分。
要么使用第一种方法(首选),要么将赋值移动到构造函数中(在这种情况下没有必要,但如果在构造对象之前不知道大小,则可能会很有用 - 然后您可以将其传递为构造函数的参数)。
int[] arrOfInt;
public ArrayExample()
{
arrOfInt = new int[SIZE];
}
关于java - 在主类或主方法中声明数组有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10573292/