[JAVA]二維數組的創建,初始化,遍歷輸出


 

整齊的二維數組 

import java.util.Random;
public class a2d
{
    public static void main(String[] args)
    {
        var rand = new Random();
        int[][] scores = new int[3][5];
        for (int i = 0; i < scores.length; ++i) //遍歷賦值
        {
            for (int j = 0; j < scores[i].length; ++j)
            {
                scores[i][j] = 60 + rand.nextInt(41); //取[60, 100]之間的隨機數
            }
        }
        for (int[] row : scores) //輸出數組元素
        {
            for (int score: row)
            {
                System.out.printf("%3d", score);
            }
            System.out.println();
        }
    }
}

 

 

ragged array的創建與初始化,遍歷

import java.util.Random;
public class a2d
{
    public static void main(String[] args)
    {
        var rand = new Random();
        //注意學習創建二維ragged array方法
        // 方法一:
        // int[][] scores = new int[3][];
        // scores[0] = new int[4];
        // scores[1] = new int[6];
        // scores[2] = new int[9];
        //方法二:
        int[][] scores = new int[][]
        {
            new int[4],
            new int[6],
            new int[9]
        };
        int num = 0; //統計成績的個數,用於后面的計算平均數
        for (int i = 0; i < scores.length; ++i) //遍歷賦值
        {
            num += scores[i].length;
            for (int j = 0; j < scores[i].length; ++j)
            {
                scores[i][j] = 60 + rand.nextInt(41); //取[60, 100]之間的隨機數
            }
        }

        int sum = 0;
        for (int[] row : scores) //輸出數組元素
        {
            for (int score: row)
            {
                System.out.printf("%3d", score);
                sum += score;
            }
            System.out.println();
        }
        System.out.println("sum = " + sum);
        System.out.println("num = " + num);
        System.out.println("average = " + (sum + .0) / num);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM