首页 > 编程语言 > 详细

[JAVA]二维数组的创建,初始化,遍历输出

时间:2020-06-14 22:43:49      阅读:48      评论:0      收藏:0      [点我收藏+]

 

整齐的二维数组 

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);
    }
}

 

[JAVA]二维数组的创建,初始化,遍历输出

原文:https://www.cnblogs.com/profesor/p/13127309.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!