繁体   English   中英

如何使用 for 循环创建二维数组并分配增量为 10 的线性值?

[英]How can I use a for loop to create a two dimensional array and assign linear values with an increment of 10?

我想使用 for 循环创建一个二维数组,并且我想以 10 的增量分配值。到目前为止,这就是我所拥有的,但我没有得到我想要的结果......

package ~/TwoDimensionalArray;

import java.util.Scanner;

public class TwoDimensionalArray {

    public static void main(String[] args) {

        int rows = 3;
        int columns = 3;

        int[][] array = new int[rows][columns];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                array[i][j] = j * 10;
                System.out.println(array[i][j]);
            }
        }

    }

}

这是我希望我的 output 成为的内容:

0   30  60
10  40  70
20  50  80

Process finished with exit code 0

这是我不断得到的:

0
10
20
0
10
20
0
10
20

Process finished with exit code 0
  • 您不应在每个数字后打印新行。
  • 您应该只在打印每一行之后打印一个新行,也就是说,在外循环的每次迭代之后。
  • 您还应该在每个数字后打印一个制表符,这样数字就不会粘在一起
  • 您应该使用公式j * 10 * rows + i * 10计算第 i 行第 j 行的数字。 这将为您提供每个 position 的正确编号。
int rows = 3;
int columns = 3;

int[][] array = new int[rows][columns];

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
        array[i][j] = j * 10 * rows + i * 10;
        System.out.print(array[i][j]); // "print" doesn't print a new line
        System.out.print("\t"); // print a tab!
    }
    System.out.println(); // print a new line here
}

也许这就是你想要的

public class TempTest {
    static final int ROW = 3;
    static final int COLUMN = 3;

    public static void main(String[] args) {
        int[][] array = new int[ROW][COLUMN];
        // assign values to array
        for (int i = 0; i < ROW; i++) {
            for (int j = 0; j < COLUMN; j++) {
                array[i][j] = 10 * (i + 3 * j);
            }
        }
        // display array
        for (int i = 0; i < ROW; i++) {
            for (int j = 0; j < COLUMN; j++) {
                System.out.print(array[i][j]);
                System.out.print(' ');
            }
            System.out.println();
        }
    }
}

结果将是

0 30 60 
10 40 70 
20 50 80 

我想你不熟悉printprintln之间的区别,后者会添加一个新行。 尝试了解更多关于 JAVA 的信息,祝你好运!

尝试这个。

int rows = 3;
int columns = 3;

int[][] array = new int[rows][columns];

for (int i = 0, v = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++, v += 10) {
        array[i][j] = v;
        System.out.print(array[i][j] + "\t");
    }
    System.out.println();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM