【问题标题】:How can I create 2D arrays in java [duplicate]如何在java中创建二维数组[重复]
【发布时间】:2013-11-22 13:37:29
【问题描述】:

我将如何设计这样的东西,在 java 中使用 2D 数组?

    A  B  C

    15 15 200
    20 20 200
    25 25 200
    30 30 200
    35 35 200
    40 40 200
    45 45 200
    50 50 200
    55 55 200
    60 60 200

      int[] A = { 15, 20, 25, 30, 35, 40, 45, 50, 55, 60 };
      int[][] name = new int[3][10];

       for (int i = 0; i < 3; i++) {
       for (int j = 0; j < 10; j++) {

       name[i][j] = A[i]; // this prints out fine
       name[i][j] = A[i]; // this also prints out fine
       name[i][j] = 200; // but when I put this piece of code, it doesn't print the two 
        //above ones but instead it prints 200 on a 10 row by 3` column table.        



        for (int j = 0; j < 10; j++) 
        System.out.println(name[0][j] + " " + name[1][j] + " " + name[2][j]);


}
}
}

一切正常,但“name[i][j] = 200;”当我放这个时,它只打印这个而不是别的

【问题讨论】:

  • 它的意思是 10 x 3(10 行和 3 列),第一行应该包含 15 15 200,第二行应该包含 20 20 200,第三行应该包含 25 25 200等等
  • 请不要将您的问题编辑为非问题。即使您的问题已经解决,它可能仍然对其他人有用。我回滚了一些编辑。

标签: java arrays multidimensional-array 2d


【解决方案1】:
new int[][] { 
  { 15, 15, 200 },
  { 20, 20, 200 },
  { 25, 25, 200 },
  { 30, 30, 200 },
  { 35, 35, 200 },
  { 40, 40, 200 },
  { 45, 45, 200 },
  { 50, 50, 200 },
  { 55, 55, 200 },
  { 60, 60, 200 } };

【讨论】:

    【解决方案2】:
    int[][] name = new int[x][y];
    

    您可以将 name 替换为您想要命名的数组,并将 xy 替换为 x 和 y 长度数组,在您的情况下,x 为 3,y 为 10。

    如果您想为其他类型(如字符串、字符等)创建一个二维数组,您可以将 int 替换为该类型的变量,这样就可以了

    String[][] = new String[x][y];
    

    如果你打印得当,它会如你所愿。看看这个例子,它应该是你要找的。​​p>

    int[][] name = new int[3][10];
    
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 10; j++) {
            name[i][j] = 0;
        }
    }
    
    for (int j = 0; j < 10; j++) 
        System.out.println(name[0][j] + " " + name[1][j] + " " + name[2][j]);
    

    在 java 文档中阅读有关数组 here 的更多信息。

    【讨论】:

    • 您好,感谢您的回复,是否可以使用 for 循环?或嵌套 for 循环。
    • 我有这个自动取款机,贴在上面
    • 那有什么问题呢?
    • 它将它们打印在一行向下而不是在 10 行乘 3 列中
    • 是的,您可以使用循环,查看我更新的示例。
    猜你喜欢
    • 2011-02-12
    • 2015-07-25
    • 2020-03-21
    • 2013-05-02
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    相关资源
    最近更新 更多