java筆記2-陣列操作
阿新 • • 發佈:2018-12-14
目錄
遍歷陣列
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] ns = { 1, 1, 2, 3, 5, 8 }; System.out.println(ns); // 類似 [[email protected] // 使用for迴圈可以遍歷陣列 for (int i = 0; i < ns.length; i++) { int n = ns[i]; System.out.println(n); } // for each迴圈直接遍歷陣列的元素 for (int n : ns) { System.out.println(n); } System.out.println(Arrays.toString(ns)); } }
陣列排序
import java.util.Arrays; public class Main { public static void main(String[] args) { /** * 冒泡法 */ int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 }; // 排序前: System.out.println(Arrays.toString(ns)); // 排序: for (int i = 0; i < ns.length; i++) { for (int j = i + 1; j < ns.length; j++) { if (ns[i] > ns[j]) { // 交換ns[i]和ns[j]: int tmp = ns[j]; ns[j] = ns[i]; ns[i] = tmp; } } } // 排序後: System.out.println(Arrays.toString(ns)); /** * 使用Arrays.sort */ int[] ns1 = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 }; // 排序前: System.out.println(Arrays.toString(ns1)); // 排序 Arrays.sort(ns1); // 排序後: System.out.println(Arrays.toString(ns)); } }
二維陣列
import java.util.Arrays; public class Main { public static void main(String[] args) { int[][] stds = { // 語文, 數學, 英語, 體育 { 68, 79, 95, 81 }, { 91, 89, 53, 72 }, { 77, 90, 87, 83 }, { 92, 98, 89, 85 }, { 94, 75, 73, 80 } }; System.out.println(stds.length); System.out.println(Arrays.toString(stds)); System.out.println(Arrays.deepToString(stds)); // TODO: 遍歷二維陣列,獲取每個學生的平均分: for (int[] std : stds) { int sum = 0; for (int s : std) { sum = sum + s; } int avg = sum / std.length; System.out.println("Average score: " + avg); } // TODO: 遍歷二維陣列,獲取語文、數學、英語、體育的平均分: int[] sums = { 0, 0, 0, 0 }; for (int[] std : stds) { sums[0] = sums[0] + std[0]; sums[1] = sums[1] + std[1]; sums[2] = sums[2] + std[2]; sums[3] = sums[3] + std[3]; } System.out.println("Average Chinese: " + sums[0] / stds.length); System.out.println("Average Math: " + sums[1] / stds.length); System.out.println("Average English: " + sums[2] / stds.length); System.out.println("Average Physical: " + sums[3] / stds.length); } }
命令列引數
命令列引數是String[]
命令列引數由JVM接收使用者輸入並傳給main方法
如何解析命令列引數由程式自己實現
public class Main {
public static void main(String[] args) {
System.out.println("Number of args: " + args.length);
for (String arg : args) {
if ("-version".equals(arg))
System.out.println("version 1.0");
}
}
}