本文介绍了使用嵌套 For 循环初始化二维数组的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化如下数组:

I am trying to format an array that is the following:

[1] [2] [3] [4] [5]
[6] [7] [8] [9] [10]
[11] [12] [13] [14] [15]

如何使用嵌套的 for 循环初始化二维数组和值?

How could I initialize the two dimensional array and the values using nested for loops?

推荐答案

我觉得你对二维数组有一个误解.想想它们是包含数组的数组.

I think you have a misunderstanding of two dimensional arrays. Think of them beeing arrays containing arrays.

如果你真的想要这个:

[[1] [2] [3] [4] [5]
[6] [7] [8] [9] [10]
[11] [12] [13] [14] [15]]

你可以这样初始化:

int[][] array2d = new int[15][1]
for (int i = 0; i < array2d.length; i++) {
    array2d[i][0] = i + 1;
}

如果在 fatc,你真正想要的是:

If in fatc, what you really want is:

[[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[11, 12, 13, 14, 15]]

你可以使用:

int[][] array2d = new int[3][5]
for (int i = 0; i < array2d.length; i++) {
    for (int j = 0; j < array2d[0].length; j++) {
        array2d[i][j] = (i * array2d[0].length) + j + 1;
    }
}

这篇关于使用嵌套 For 循环初始化二维数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:20