二十三:Java基础入门-Java数组

2019-07-15  本文已影响0人  Lord丶轩莫言弃

1、数组的定义

2、数组的分类

3、数组的优点

注意:上述代码是伪代码,下面将详细说明数组的使用。

4、数组的声明

public static void main(String args[]) {
    int[] score = null;// 数组的声明
    score = new int[3];// 为数组开辟内存空间,实例化

    // 数组下标是从0开始的
    for (int i = 0; i < score.length; i++) {
        score[i] = i * 2 + 1;
    }

    for (int i = 0; i < score.length; i++) {
        System.out.println(score[i]);
    }
}

5、数组静态初始化

public static void main(String args[]) {
    // 静态初始化
    int[] score = { 1, 2, 3, 4, 5, 6 };// 数组的声明
    for (int i = 0; i < score.length; i++) {
        System.out.println(score[i]);
    }
}

6、数组的使用

public static void main(String args[]) {
    int[] score = { 41, 52, 83, 34, 65 };
    int max, min;
    max = min = score[0];
    for (int i = 0; i < score.length; i++) {
        if (score[i] > max) {
            max = score[i];
        }
        if (score[i] < min) {
            min = score[i];
        }
    }
    System.out.println("最大值:" + max);
    System.out.println("最小值:" + min);
}
/**
 * 冒泡排序(Java 经典面试算法)
 * @param args
 */
public static void main(String args[]) {
    int[] score = { 41, 52, 83, 34, 65 };
    for (int i = 0; i < score.length - 1; i++) {
        for (int j = i + 1; j < score.length; j++) {
            if (score[i] < score[j]) {
                int temp = score[i];
                score[i] = score[j];
                score[j] = temp;
            }
        }
    }

    for (int i = 0; i < score.length; i++) {
        System.out.println(score[i]);
    }
}

7、二维数组声明内存分配介绍及使用

public static void main(String args[]) {
    int[][] score = new int[5][5];
    score[0][0] = 9;
    score[0][3] = 8;
    score[3][2] = 7;

    for (int i = 0; i < score.length; i++) {
        for (int j = 0; j < score[i].length; j++) {
            System.out.print(score[i][j] + " ");
        }
        System.out.println();
    }
}
public static void main(String args[]) {
    int[][] score = { { 100, 90 }, { 67, 70 }, { 50, 78, 80 } };

    for (int i = 0; i < score.length; i++) {
        for (int j = 0; j < score[i].length; j++) {
            System.out.print(score[i][j] + " ");
        }
        System.out.println();
    }
}

注意:在日常开发中,二维数组使用情况比较少,熟悉即可。

说明:该内容由Lord丶轩莫言弃收集整理,参考资料来源于极客学院

上一篇 下一篇

猜你喜欢

热点阅读