一.什么是數組:
數組是一個變量,存儲相同數據類型的一組數據
聲明一個變量就是在內存空間划出一塊合適的空間
聲明一個數組就是在內存空間划出一串連續的空間
二.數組基本要素:
標識符:數組的名稱,用於區分不同的數組
數組元素:向數組中存放的數據
元素下標:對數組元素進行編號,從0開始,數組中的每個元素都可以通過下標來訪問
元素類型:數組元素的數據類型
注意:數組長度固定不變,避免數組越界
三:使用數組的步驟:
1.聲明數組:告訴計算機數據類型是什么 int [] a;
語法:
數據類型 數組名[ ] ;
數據類型[ ] 數組名 ;
2.分配空間:告訴計算機分配幾個連續的空間 a=new int[5];
語法:
數據類型[ ] 數組名 = new 數據類型[大小] ;
3.賦值:向分配的格子里放數據 a[0]=8;
3.1 邊聲明邊賦值
int[ ] score = {89, 79, 76};
int[ ] score = new int[ ]{89, 79, 76}; 不能指定數組長度
3.2 動態地從鍵盤錄入信息並賦值
Scanner input = new Scanner(System.in);
for(int i = 0; i < 30; i ++){
score[i] = input.nextInt();
}
4.處理數據:計算5位學生的平均分 a[0]=a[0]*10;
int [ ] score = {60, 80, 90, 70, 85};
double avg;
avg = (score[0] + score[1] + score[2] + score[3] + score[4])/5;
數組名.length代表數組的長度
案例:計算全班學員的平均分 public class Demo01 { public static void main(String[] args) { //存儲30名學員的成績 int [] score=new int[5]; double avg=0.0; //平均分 double sum=0; //成績總和 Scanner input=new Scanner(System.in); //.length:代表了數組的長度 30 for (int i = 0; i < score.length; i++) { System.out.println("請輸入第"+(i+1)+"位學員的成績:"); score[i]=input.nextInt(); //每一次循環計算總和 sum=sum+score[i]; } avg=sum/score.length; System.out.println("平均分:"+avg); } }
四.數組排序:
升序:Arrays.sort(數組名); 從0到最大
降序:升序拍列完畢后 從最大到0
案例:升序he降序拍列成績 public class Demo02 { public static void main(String[] args) { //定義一個數組,存儲5位學員的成績 int [] score=new int[]{98,56,74,85,100}; System.out.println("5位學員的初始成績:"); for (int i = 0; i < score.length; i++) { System.out.print(score[i]+"\t"); } System.out.println(); System.out.println("5位學員的升序拍列后的成績:"); //升序拍列 Arrays.sort(score); for (int i = 0; i < score.length; i++) { System.out.print(score[i]+"\t"); } System.out.println(); System.out.println("5位學員的降序拍列后的成績:"); //降序:從后往前打印 //score.length-1:數組最大下標 for (int j = score.length-1; j>=0; j--) { System.out.print(score[j]+"\t"); } } }