- 一、一维数组的创建和使用
- 1.创建一维数组
- 2.使用一维数组
- 二、二维数组的创建和使用
- 1.创建二维数组
- 2.使用二维数组
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[4];
(2)声明的同时为数组分配内存
数组元素类型 数组名 = new 数组元素类型[元素个数][元素个数]
(3)二维数组的初始化
type arrayname[][] = {value1,value1.....};
2.使用二维数组
采用同样示例简要说明;
public class TestArr2{
public static void main(String args[]) {
int a[][] = new int[3][4];
for(int i=0;i
实验结果:
0
0
0
0
-----------------------
0
0
0
0
-----------------------
0
0
0
0
-----------------------



