數組:
格式:數據類型 + [] + 變量名 = new + 數據類型 + []{};
數組的長度固定不變,避免數組越界.
數組越界報錯:
數組有哪些特點呢?
1):同類型數據
2):分配連續空間的一個變量
數組的四大步驟:
1):聲明數組
2):開空間(定義數組個數)
3):賦值
4):處理應用
數組賦值的幾種方法:
1):邊開空間邊賦值 例: int [] score = new int[]{};
2):先聲明,在開空間賦值 例: int[] score;
Score = new int[]{};
3):邊聲明邊賦值 例: int[] score = {1,3,5,7,9} //知道數據的值推薦使用此方法
4):輸入法賦值 例: int [] score = new int[12];
for(int i = 0; i < score.length; i++){
System.out.println(“請輸入第” + (i+1) + “個數組的值”);
Score[i] = input.NextInt();
}
數組的輸出:
1.數組按升序排列:系統知道方法:Arrays.sort(數組名)
例:
2.查找數組的最大/最小值;
public class A_CeShi {
public static void main(String[] args) {
int[] score = { 10, 18, 94, 2, 56, 74, 3, 105 }; // 定義一個數組
int max = score[0];// 假如最大值為第一個數
int least = score[0];// 假如最小值為第一個數
for (int i = 0; i < score.length; i++) {
if (max < score[i]) { // 把定義的最大數跟每個數比較
max = score[i]; // 如果比最大數大則把該值賦給最大值
}
if (least > score[i]) { // 相反
least = score[i];
}
}
System.out.println("該數組的最大值為:" + max);
System.out.println("該數組的最小值為:" + least);
}
}
3.插入算法:
Scanner input = new Scanner(System.in);
int[] list = new int[6];//成績必須有序的排列,否則循環格式不成立
list[0] = 99;
list[1] = 85;
list[2] = 82;
list[3] = 63;
list[4] = 60;
System.out.print("請輸入要插入的學生的成績:");
int num = input.nextInt(); // 定義要插入的成績
int index = 0;// 假如位置在排名的第一個
for (int i = 0; i < list.length; i++) { // 把插入的成績跟每個人的成績比較
if (num > list[i]) {
index = i;
break;
}
}
for(int j = list.length - 1;j > index;j--){ //插入的成績位置比原成績的位置小
list[j] = list[j-1]; //則把該同學的成績位置往后移動一位
}
list[index] = num;
System.out.print("插入后的學生排名是:");
for(int i = 0;i < list.length;i++){
System.out.print(list[i] + " ");
}
Arrays類常用方法(數組工具類):