0

数组的相同类型的声明在其外部时显示错误,main()但在内部时符合且没有错误main()

public class Array {
    int arr1[];
    arr1 = new int[10]; // shows <identifier> expected error

    public static void main(String args[]){
        int arr2[];
        arr2 = new int[10];
    }
}
4

4 回答 4

0

在任何 Java 类中,第一部分是声明部分。用于声明对象。

它不包含任何指定操作的任何代码,例如为变量赋值、进行数学运算等。

在这里你正在初始化数组arr1

arr1 = new int[10];

在函数之外。如果你真的想做一个初始化,你可以这样做

int arr1 = new int[10];

它在创建时初始化数组。否则,您可以在任何方法中对其进行初始化。它不需要成为主要功能。

这是因为,函数是一组需要执行的代码,而一个类是一组对象和相关函数。

public class Array {
    int arr1[];

    public String anyFunction(){
        arr1 = new int[10];
    }
}

这里formare关于类的细节。

于 2013-08-20T09:41:59.277 回答
0

当你在单独的行中声明它时它不起作用,因为它原来是一个语句。语句只允许在静态块、方法和构造函数中。

这很好用,因为它是字段声明

int a[]= {1,2,3};
int a[]=new int[]{1,3,4,5};

您可能希望使用对象访问这些对象,因为它们是非静态字段。

于 2013-08-20T09:26:56.250 回答
0

当你想给一个变量赋值时,你应该在定义它时这样做

private int arr1 = new int[10];

或在方法内部(例如'main')。

public class TestClass {
   // When you want to use the variable inside a static function, arr1 should be declared as static
   private static int arr1[] = new int[10];

   public static void main(String args[]) {
      arr1 = new int[10];
   }
}

阅读内容以了解类/成员变量基础知识。

于 2013-08-20T09:11:26.160 回答
0

这可以在一行中完成,例如:

int arr1 = new int[10];

如果您需要多个语句,则需要将代码放在方法、构造函数或初始化程序块中。

于 2013-08-20T09:07:19.693 回答