Java基础题——二维数组

问题描述

随机产生一个5x5的二维数组(输出的数字必须大于零,小于十)
问题: 输出该随机数组
1.求出对角线上的数字总和(注意交点上的数字不能重复计算)
2.将数组对角线上的数字换成【*】

样列:
// 1 6 6 6 6
// 1 2 3 4 5
// 1 6 5 4 3
// 1 2 2 2 2
// 2 5 5 5 5

// 29

// * 6 6 6 *
// 1 * 3 * 5
// 1 6 * 4 3
// 1 * 2 * 2
// * 5 5 5 *

代码

package YRZ;
public class YRZ01 {
    public static void main(String[] args) {
        int m = 5;
        int n = 5;
        int[][] arr = new int[m][n]; //构建一个空的二维数组
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] =(int) (Math.random() * 9) + 1;
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
        int s = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (i == j || i + j == arr[i].length-1) {
                    s += arr[i][j];
                }
            }
        }
        System.out.println(s);
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (i == j || i + j == arr[i].length-1) {
                    System.out.print("*" + " ");
                }else{
                    System.out.print(arr[i][j]+" ");
                }
            }
            System.out.println();
        }
    }
}
发布了53 篇原创文章 · 获赞 56 · 访问量 1418

猜你喜欢

转载自blog.csdn.net/duwenyanxiaolaji/article/details/104149697
今日推荐