如何初始化Java中的数组? [英] How to initialize an array in Java?
问题描述
我初始化数组的数据是这样的:
公共类Array { int数据[] =新INT [10];
/ **创建阵列的一个新实例* /
公共阵列(){
数据[10] = {10,20,30,40,50,60,71,80,90,91};
}}
NetBeans的在该行指出一个错误
数据[10] = {10,20,30,40,50,60,71,80,90,91};
我该如何解决这个问题呢?
数据[10] = {10,20,30,40,50,60,71,80,90, 91};
以上是不正确(语法错误)。这意味着你分配一个数组数据[10]
可容纳只是一个元素。
如果您要初始化数组,请尝试使用阵列初始化:
INT []数据= {10,20,30,40,50,60,71,80,90,91};// 要么INT []数据;
数据= INT新[] {10,20,30,40,50,60,71,80,90,91};
注意两个声明之间的差异。当分配一个新的数组已声明的变量,新
必须使用。
即使你更正语法,访问数据[10]
仍是不正确的(你只能访问数据[0]
到数据[9]
因为Java数组的索引是基于0的)。访问数据[10]
将抛出一个<一个href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/ArrayIndexOutOfBoundsException.html\">ArrayIndexOutOfBoundsException.
I am initializing an array data like this :
public class Array {
int data[] = new int[10];
/** Creates a new instance of Array */
public Array() {
data[10] = {10,20,30,40,50,60,71,80,90,91};
}
}
NetBeans points an error at the line
data[10] = {10,20,30,40,50,60,71,80,90,91};
How can I solve the problem?
data[10] = {10,20,30,40,50,60,71,80,90,91};
The above is not correct (syntax error). It means you are assigning an array to data[10]
which can hold just an element.
If you want to initialize an array, try using Array Initializer:
int[] data = {10,20,30,40,50,60,71,80,90,91};
// or
int[] data;
data = new int[] {10,20,30,40,50,60,71,80,90,91};
Notice the difference between the two declarations. When assigning a new array to a declared variable, new
must be used.
Even if you correct the syntax, accessing data[10]
is still incorrect (You can only access data[0]
to data[9]
because index of arrays in Java is 0-based). Accessing data[10]
will throw an ArrayIndexOutOfBoundsException.
这篇关于如何初始化Java中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!