Learn JAVA from scratch (04): array

First, the characteristics of the array

  • An array is a collection of variables of the same type, and all elements are of the same type
  • You can specify the number of elements contained in the array, up to the maximum value of int
  • elements have a fixed order
  • Each element has a fixed number, called the index (index), increasing from 0, the type is int
  • Any element in the array can be read and written like a variable

2. Syntax for creating and using an array

  • Array element type [] variable name = new array element type [array length]
  • Variable name [index] You can use this variable, you can read it or assign a value to it

3. Array practice

public class CreateArray {
    public static void main(String[] args) {
        int[] intArray = new int[100]; // 长度为100的数组
        System.out.println(intArray[10]); // 如果没有赋值,默认值为0

        double[] doubleArray = new double[100];
        System.out.println(doubleArray[20]); // 如果没有赋值,默认值为0.0

        intArray[20] = 100;
        System.out.println(intArray[20]);

        // 数组越界
        // 报错:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 101 out of bounds for length 100
        System.out.println(intArray[101]);
    }
}

Fourth, the name and reality of the array

  • The "real" of the array is a piece of memory with continuous addresses, just like white paper with continuous numbers
  • The name of the array is the address of the first memory of this block of continuous memory
  • The data variable is the same as the basic variable, which itself is an address, but unlike the variable, the value of this address is the "name" of the array, which is the first address of the array
  • Array = array variable + array entity
  • The array variable [index] is to add the index to the original address of the array to obtain the desired element
  • So the index starts from 0, because the address of the array variable is the address of the first element of the array

Five, the length of the array

  • The array variable .length can get the length of the array
  • Unlike JavaScript, once an array in java is created, its length is immutable
  • Array out of bounds error is ArrayIndexOutOfBoundsException
  • Each element in the array has an initial value, and the initial value is related to the type. For int, the initial value is 0; for Boolean, the initial value is false
  • Array variables can point to new array entities. At this time, the value of the array variable is the address of the new array entity
  • If no other array variable points to the original array entity, the original array entity is inaccessible
public class CreateArray {
    public static void main(String[] args) {
        int[] intArray = new int[100]; // 长度为100的数组
        System.out.println(intArray.length);
    }
}
public class CreateArray {
    public static void main(String[] args) {
        int[] intArray = new int[100]; // 长度为100的数组
        System.out.println(intArray.length); // 100

        intArray = new int[10];
        System.out.println(intArray.length); // 10
    }
}

Six, two-dimensional array

  • Two-dimensional arrays are an extension of one-dimensional arrays
  • double[][] double2Array = new double[5][10]
public class CreateArray {
    public static void main(String[] args) {
        double[][] double2Array = new double[5][3];
        for (int i = 0; i < double2Array.length; i++) {
            for (int j = 0; j < double2Array[i].length; j++) {
                double2Array[i][j] = Math.random() * 100;
                System.out.println(double2Array[i][j]);
            }
        }
    }
}

Seven, a program

import java.util.Scanner;

public class ScoreMaster {
    public static void main(String[] args) {

        // 声明六个变量, 分别代表六门科目的成绩
        int YuWenIndex = 0;
        int ShuXueIndex = 1;
        int WaiYuIndex = 2;
        int WuLiIndex = 3;
        int HuaXueIndex = 4;
        int ShengWuIndex = 5;

        int totalScoreCount = 6;

        // 每门课的名字
        String[] names = new String[totalScoreCount];
        names[YuWenIndex] = "语文";
        names[ShuXueIndex] = "数学";
        names[WaiYuIndex] = "外语";
        names[WuLiIndex] = "物理";
        names[HuaXueIndex] = "化学";
        names[ShengWuIndex] = "生物";

        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入共有多少年的成绩:");

        int yearCount = scanner.nextInt();

        double[][] scores = new double[yearCount][totalScoreCount];

        for (int i = 0; i < yearCount; i++) {
            for (int j = 0; j < totalScoreCount; j++) {
                scores[i][j] = 80 + Math.random() * 20;
                System.out.println("第" + (i + 1) + "年" + names[j] + "成绩为:" + scores[i][j]);
            }
        }

        boolean cont = true;
        while (cont) {
            System.out.println("请选择要进行的操作:");
            System.out.println("1: 求某年最好成绩\n" +
                "2: 求某年的平均成绩\n" +
                "3: 求所有年份最好成绩\n" +
                "4: 求某门课历年最好成绩");

            int oprtId = scanner.nextInt();

            int year = 0;
            switch (oprtId) {
                case 1:
                    // 让用户输入指定的年份
                    System.out.println("请输入要计算第几年的最好成绩");
                    year = scanner.nextInt();
                    if (year <= 0 || yearCount < year) {
                        System.out.println("非法的年份:" + year);
                        cont = false;
                        break;
                    }
                    year = year - 1;
                    // 指定年份的最好成绩的编号,开始假设是0
                    int bestOfYearScoreId = 0;
                    // 循环指定年份的成绩,找出最好的成绩
                    // TODO:如果有两门课的成绩一样,而且都是最高的,怎么办?
                    for (int i = 1; i < totalScoreCount; i++) {
                        if (scores[year][bestOfYearScoreId] < scores[year][i]) {
                            bestOfYearScoreId = i;
                        }
                    }
                    System.out.println("第" + (year + 1) + "年成绩最好的科目为" + names[bestOfYearScoreId] + ",成绩为" + scores[year][bestOfYearScoreId] + "。");
                    break;
                case 2:
                    System.out.println("请输入要计算第几年的平均成绩");
                    year = scanner.nextInt();
                    if (year <= 0 || yearCount < year) {
                        System.out.println("非法的年份:" + year);
                        cont = false;
                        break;
                    }
                    year = year - 1;
                    double totalCountForAvg = 0;
                    for (int i = 0; i < totalScoreCount; i++) {
                        totalCountForAvg += scores[year][i];
                    }
                    double avgOfYear = totalCountForAvg / totalScoreCount;
                    System.out.println("第" + (year + 1) + "年的平均成绩为" + avgOfYear + "。");
                    break;
                case 3:
                    int bestYear = 0;
                    int bestScore = 0;

                    for (int i = 0; i < yearCount; i++) {
                        for (int j = 0; j < totalScoreCount; j++) {
                            if (scores[bestYear][bestScore] < scores[i][j]) {
                                bestYear = i;
                                bestScore = j;
                            }
                        }
                    }
                    // 视频中代码有错误,应该是使用 bestYear 而不是 year
                    System.out.println("所有年度最好成绩为第" + (bestYear + 1) + "年的" + names[bestScore] + ",成绩为" + scores[bestYear][bestScore] + "。");
                    break;
                case 4:
                    System.out.println("请输入科目编号");
                    int subjectId = scanner.nextInt();
                    if (subjectId <= 0 || totalScoreCount < subjectId) {
                        System.out.println("非法的科目编号:" + subjectId);
                        cont = false;
                        break;
                    }
                    subjectId = subjectId - 1;
                    year = 0;
                    for (int i = 1; i < yearCount; i++) {
                        if (scores[year][subjectId] < scores[i][subjectId]) {
                            year = i;
                        }
                    }
                    System.out.println("第" + (year + 1) + "年度" + names[subjectId] + "成绩最好,为" + scores[year][subjectId] + "。");

                    break;
                default:
                    cont = false;
                    System.out.println("不支持:" + oprtId + ", 程序结束。");
            }
        }

    }
}

Guess you like

Origin blog.csdn.net/m0_47135993/article/details/128088038