1.数组是多个相同类型数据的组合,实现对数据统一管理。
2.数组是引用类型,数组型数据是对象,数组中每个元素相当于该对象的成员变量。
使用数组:
1.数组初始化:
int[] scores1 = new int[](72,89,90) //静态初始化:在声明并初始化数组与给相应的元素进行赋值操作同时进行。
int[] scores2 = new int[3]; //动态初始化:在声明并初始化数组与给相应的元素赋值操作进行分开。
scores2[0] = 72;
scores2[1] = 89;
scores2[2] = 90;
注:不管是动态还是静态初始化数组,一定在创建的时候,就指明了数组的长度。
2.如何引用数组元素:通过数组的下角标的方式。下角标从0开始,到n-1结束。其中n为
为数组的长度。
3.数组的长度:通过数组的属性length来调用。
System.out.println(scores2.length);
4.如何遍历数组
for(int i =0;i < scores1.length;i++){
System.out.println(scores1[i]);
}
5.数组的初始化值
//对于基于基本数据类型的变量创建的数组:bytes short int long float double char boolean
// 1.对于byte short int long 而言,创建数组以后,默认值为0
//2.对于float double而言,创建数组以后,默认值为0.0
//3.对于char而言,默认为空格
//4.对于boolean而言,默认为flase
//3.对于引用类型的变量构成的数组而言,默认值为null
注:数据一旦创建以后,长度不可变。
多维数组(二维数组):
public class TestArray {
public static void main(String[] args){
int[] scores1 =new int[10];
int[][] scores2;
String[][] names;
//1.二维数组的初始化
scores2 = new int[][]{{1,2,3},{4,5,6},{7}};
names = new String[6][5];//动态初始化一
names = new String[6][0];//动态初始化二
names[0] = new String[7];
names[1] = new String[6];
names[2] = new String[5];
names[3] = new String[5];
names[4] = new String[4];
names[5] = new String[3];
//错误的初始化方式;
// names =new String[][];
// names =new String[][6];
//2.如何引用具体的某个元素
int[][] i = new int[3][2];
i[1][0] = 90;
i[2][1] = 100;
//3.数组的长度,length属性
System.out.println(i.length);//3
System.out.println(i[0].length);//2
//4.如何遍历二维数据
for(int m = 0;m <scores2.length;m++ ){
for(int n = 0;n <scores2[m].length;n++){
System.out.print(scores2[m][n]);
}
System.out.println();
}
}
}
数组异常
package com.yuanwang.java;
public class TestException {
public static void main(String[] args){
int[] i = new int[10];
i[0] = 90;
//1.数组下标越界异常:java.lang.ArrayIndexOutOfBoundsException
// i[10] = 99;
// for(int m = 0;m <=i.length;m++){
// System.out.println(i[m]);
// }
//2.空指针的异常:java.lang.NullPointerException
//堆中为空,或者栈为空,没有方法。
//第一种:
boolean[] b = new boolean[3];
b =null;
//b的指针为空;
System.out.println(b[0]);
//第二种:
//str[3]为空,没有toString()
String[] str =new String[4];
System.out.println(str[3].toString());
//第三种:
//j[2]是null,没有地址。
int[][] j = new int[3][];
j[2][0] = 12;
}
}
杨辉三角
public class Yahui {
public static void main(String[] args){
int[][] yanghui =new int[10][];
for(int m =0;m < yanghui.length;m++){
yanghui[m] = new int[m+1];
}
for(int i =0;i < yanghui.length;i++){
for(int j = 0;j <= yanghui[i].length;j++){
yanghui[i][0] = yanghui[i][i] = 1;
if(i > 1 && j > 0 && j < i){
yanghui[i][j] = yanghui[i-1][j-1]+yanghui[i-1][j];
}
}
}
for(int i =0;i < yanghui.length;i++){
for(int j = 0;j < yanghui[i].length;j++){
System.out.print(yanghui[i][j]+"\t");
}
System.out.println();
}
}
}