1.4数组操作

    技术2022-07-10  137

    遍历数组

    for循环for(int i = 0;i<n.length;i++){System.out.println(n[i]);}for each循环for(Object obj:n){System.out.println(obj);}

    数组排序

    冒泡排序:

    public static void main(String[] args) { int[] ns = { 1,3,59,165,1,3,61,65,165,1,5416,1,561,3,15,3,1 }; Hello hello = new Hello();//创建对象 hello.mpsortArr(ns);//调用排序方法 hello.toStringArr(ns);//调用输出 } //输出校验 public void toStringArr(int[] n) { for (int i = 0; i < n.length; i++) { System.out.print(n[i]+" "); } } //冒泡排序:将数组中的每一个前者与后者比较,若前者大则交换,一共比较n.length次。将上步骤循环n.length-1次,每一次都将最大的数放在最后,最终排序成功。 public void mpSortArr(int[] ns) { for (int i = 0; i < ns.length-1; i++) {//循环遍历数组,需要ns.length边遍历,每次遍历将最大的数放到最后 for (int j = 1; j < ns.length-i; j++) {//每次进行比较都比上一次比较的次数少1 if(ns[j]>ns[j-1]) {//比较两个相邻的数,较大的数往后排 int t = ns[j-1]; ns[j-1] = ns[j]; ns[j] = t; } } } }

    二维数组

    定义:(ns.length = 3,因为其包含了三个数组) int[][] ns = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; 二维数组输出: 嵌套for循环。 for (int[] arr : ns) { for (int n : arr) { System.out.print(n); System.out.print(', '); } System.out.println(); } 三维数组(多维数组): int[][][] ns = { { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }, { {10, 11}, {12, 13} }, { {14, 15, 16}, {17, 18} } };

    命令行参数

    main方法中,args[]用来接收命令行参数(即JVM接收用户输入并传给main方法) 示例:

    public class Main { public static void main(String[] args) { for (String arg : args) { if ("-version".equals(arg)) { System.out.println("v 1.0"); break; } } } }
    Processed: 0.010, SQL: 9