多維數組


上面這張表格其實是一個n行*6列的二維數組。java

多維數組的語法:

double[] arrayName = double[n]; // (一維)數組,數組長度爲n
double[][] dimensionArrayName = double[m][n]; // 二維數組(m行 * n列)
double[][][] threeDimensionArrayName = double[x][y][z] // 三維數組

注意:每個中括號表示一個維度。數組

習題

設計一個程序,能夠保存n年的各科成績,能夠對這些年的成績進行查詢。
測試用例:保存3年的成績,查詢第三年的生物成績。dom

import java.util.Scanner;

public class Example2 {
    public static void main(String[] args) {
        // 爲每一門課程設置下標
        int ChineseIndex = 0;
        int MathIndex = 1;
        int EnglishIndex = 2;
        int PhysicalIndex = 3;
        int ChemistryIndex = 4;
        int BiologyIndex = 5;

        // 建立一個數組保存每一門課的名稱
        String[] names = new String[6];
        names[ChineseIndex] = "語文";
        names[MathIndex] = "數學";
        names[EnglishIndex] = "英語";
        names[PhysicalIndex] = "物理";
        names[ChemistryIndex] = "化學";
        names[BiologyIndex] = "生物";

        Scanner in = new Scanner(System.in);
        System.out.println("存放幾年的成績呢?");
        int years; // 存放成績多少年的年數
        years = in.nextInt();

        // 建立一個二維數組來存放每門課的成績 行表示年數,列表示科目數
        double[][] scores = new double[years][names.length];

        // 隨機生成80-100的成績放入二維數組中
        for (int i = 0; i < years; i++) {
            for (int j = 0; j < names.length; j++) {
                scores[i][j] = 80 + Math.random() * 20;
                System.out.println("第" + (i + 1) + "年的" + names[j] + "成績爲:" + scores[i][j]);
            }
        }

        // 查詢某一年的某一課程的成績
        System.out.println("您要查詢哪一年的成績呢?");
        int whichYear = in.nextInt() - 1;
        System.out.println("哪一門成績呢?");
        int whichLesson = in.nextInt() - 1;

        System.out.println("第" + (whichYear + 1) + "年的" + names[whichLesson] + "成績爲" + scores[whichYear][whichLesson]);
    }
}


相關文章
相關標籤/搜索