在Java中,數組的定義和賦值可以通過以下幾種方式進行:
dataType[] arrayName = new dataType[arraySize];
例如:
int[] numbers = new int[5];
dataType[] arrayName = {value1, value2, value3, ...};
例如:
int[] numbers = {1, 2, 3, 4, 5};
首先聲明數組,然后為每個元素賦值:
dataType[] arrayName;
arrayName = new dataType[arraySize];
arrayName[0] = value1;
arrayName[1] = value2;
...
例如:
int[] numbers;
numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
dataType[] arrayName = new dataType[arraySize];
for (int i = 0; i < arraySize; i++) {
arrayName[i] = someValue;
}
例如:
int[] numbers = new int[5];
for (int i = 0; i < 5; i++) {
numbers[i] = i + 1;
}