数组的概念:
同一类型数据的集合,其实数组就是一个容器。
数组的好处:
可以自动给数组中的元素从0开始编号,方便操作这些元素。
数组的格式:
1、元素类型 [ ] 数组名 = new 元素类型 [元素个数或数组长度]
示例:
int[] arr =new int [5];
2、元素类型 [] 数组名 = new 元素类型 [ ] {元素,元素,……};
示例:
int [] arr = new int [] {1,3,5,7};
int [] arr = {1,3,5,7};
*数组的定义方式:
int [ ] arr = new int [3]; //通过new关键字创建了一个长度为3,数组实体,元素类型是int
每一个实体都有一个首地址值,堆内存中的变量都有一个初始化值,不同类型不一样:int为0,double为0.0,Boolean为 false,当实体不再使用时就会被垃圾回收机制处理。
常见错误:
OutOfBoundsException:访问到了数组不存在的索引时,会发生该异常;
NullPointerException:当使用没有任何实体指向的引用变量操作实体时,运行会发生该异常。
举两个例子:
①、三个数取最大
int a = 3, b =4, c = 5;
int tempMax = a>b?a:b;
int max = tempMax>c?tempMax:c;
②、九九乘法表
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9 //For 嵌套循环,
for (int x=1;x<=9;x++)
{
for(int y=1;y<=x;y++)
{
System.out.print(y+"*"+"+x+"+y*x+"\t"); // \t:制表符
}
System.out.println(); //换行
}