###### tags: `Java 學習筆記` # Java 學習筆記 - 5-1: 陣列的應用 ## 陣列的記憶體配置 ### 記憶體管理 陣列一旦被創建,長度就不能被改變,同時也是一塊連續的記憶體 ## 讓 Array 擴充的方法: 建立一個新的並將舊的資料放進去 通常會根據 2 倍逐漸擴大 ```java= public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; System.out.println(arr.length); // 5 arr = doubleArr(arr); System.out.println(arr.length); // 10 } public static int[] doubleArr(int[] arr) { int[] newArr = new int[arr.length * 2]; for (int i = 0; i < arr.length; i++) { newArr[i] = arr[i]; } return newArr; } ``` ### 範例: 輸入學生成績 ```java= public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] students = new int[2]; int count = 0; while (true) { System.out.println("請輸入第" + (count + 1) + "筆成績"); int input = sc.nextInt(); if (input == -1) { break; } if (input < 0 || input > 100) { continue; } if (count == students.length) { students = doubleArr(students); } students[count++] = input; } for (int i = 0; i < count; i++) { System.out.print(students[i] + " "); } } public static int[] doubleArr(int[] arr) { int[] newArr = new int[arr.length * 2]; for (int i = 0; i < arr.length; i++) { newArr[i] = arr[i]; } return newArr; } ``` ## 資料排序 ### 氣泡排序法 * 第零個跟第一個比,每一格逐格比較,比較小的往前移 * 陣列有 n 個,連續交換 n - 1 次 ```java= for i = 1 ~ n - 1 // pass 次數 for j = 0 ~ n - i - 1 // 交換次數 if a[j] > a[j+1] then swap a[j] and a[j+1] end if end for end for ``` ## 查字典 1. 讓使用者輸入一堆字串並存到陣列 ```java= Scanner sc = new Scanner(System.in); String[] strs = new String[2]; int count = 0; String[] dictionary = new String[2]; // 出現過的字 int[] dicNum = new int[2]; //出現過幾次 int dicCount = 0; while(true) { String str =sc.nextLine(); if (str.equals("-1")) { // 字串判斷要用equals break; } int index = findIndexWithKey(dictionary, str, dicCount); if (index == -1) { if (dicCount == dictionary.length) { dictionary = StringDoubleArr(dictionary); dicNum = NumberDoubleArr(dicNum); } dictionary[dicCount] = str; index = dicCount++; } dicNum[index]++; } for (int i = 0; i < dicCount++) { System.out.println("字串: " + dictionary[i] + "\t\t出現" + dicNum[i] + "次") } public static int findIndexWithKey(String[] arr, String key, int count) { for (int i = 0; i < count; i++) { if (arr[i].equals(key)) { return i; } } return -1; } public static int[] doubleArr(int[] arr) { int[] newArr = new int[arr.length * 2]; for (int i = 0; i < arr.length; i++) { newArr[i] = arr[i]; } return newArr; } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up