一维数组的创建和使用
1、创建一维数组
(1)先声明,再用new运算符进行内存分配
声明的方法有以下两种:
数组元素类型 数组名字[]
数组元素类型[] 数组名字
内存分配格式:
数组名 = new 数组元素类型[数组元素的个数];
(2)声明的同时为数组分配内存
数组元素类型 数组名 = new 数组元素类型[数组元素个数]
(3)一维数组的初始化
有以下两种方式:
int arr[] = new int[]{1,2,3,5};
int arr2[] = {23,12,3,123,2}
2、一维数组的使用
通过以下示例可以明白一维数组的使用:
public class TestArr1 {
public static void main(String args[]) {
int day[] = new int[] {31,28,31,30,31,30,31,31,30,31,30,31};
for(int i = 0;i<12;i++) {
System.out.println((i+1)+"月有"+day[i]+"天");
}
}
}
/*输出结果如下:
1月有31天
2月有28天
3月有31天
4月有30天
5月有31天
6月有30天
7月有31天
8月有31天
9月有30天
10月有31天
11月有30天
12月有31天
*/
二维数组的创建和使用
1、二维数组的创建
(1)先声明,再使用new运算符进行内存分配
声明的语法有以下两种:
数组元素类型 数组名字[][];
数组元素类型[][] 数组名字;
内存分配方法有以下两种:
1、直接为每一维分配内存空间
a = new int[2][4];
2、分别为每一维分配内存空间
a = new int[2][];
a[0] = new int[2];
a[1] = new int[3];
(2)声明的同时为数组分配内存
数组元素类型 数组名 = new 数组元素类型[数组元素个数][数组元素个数];
(3)二维数组的初始化
type arrayname[][] = {value1,value2......};
2、二维数组的使用
同样采用示例的方法来简要的说明二维数组的使用方法:
public class TestArr2 {
public static void main(String args[]) {
int a[][] = new int[3][4];
for(int i=0;i<a.length;i++) {
for(int j=0;j<a[i].length;j++) {
System.out.println(a[i][j]);
}
System.out.println("-----------------------");
}
}
}
/*输出结果如下:
0
0
0
0
-----------------------
0
0
0
0
-----------------------
0
0
0
0
-----------------------
*/