標籤:數組元素 學生 for string 標識符 stat 變數 數組越界 ++
一.什麼是數組:
數組是一個變數,儲存相同資料類型的一組資料
聲明一個變數就是在記憶體空間划出一塊合適的空間
聲明一個數組就是在記憶體空間划出一串聯續的空間
二.數組基本要素:
標識符:數組的名稱,用於區分不同的數組
數組元素:向數組中存放的資料
元素下標:對數組元素進行編號,從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");
}
}
}
Java新幫派——數組