for循环-双维数组Java



我的代码运行得很好,尽管我不知道如何在单词"row"之前打印行号。应该是第1行、第2行,依此类推。有什么线索可以告诉你怎么做吗?还有一个以更简单的方式存储这些字符串的线索。谢谢你:(

System.out.println("t A t B t C t D t E t F");
String [][] TwoDim = new String[13][6];
TwoDim[0][0] = "*";
TwoDim[0][1] = "*";
TwoDim[0][2] = "X";
TwoDim[0][3] = "*";
TwoDim[0][4] = "X";
TwoDim[0][5] = "X";
TwoDim[1][0] = "*";
TwoDim[1][1] = "X";
TwoDim[1][2] = "*";
TwoDim[1][3] = "X";
TwoDim[1][4] = "*";
TwoDim[1][5] = "X";
TwoDim[2][0] = "*";
TwoDim[2][1] = "*";
TwoDim[2][2] = "X";
TwoDim[2][3] = "X";
TwoDim[2][4] = "*";
TwoDim[2][5] = "X";
TwoDim[3][0] = "X";
TwoDim[3][1] = "*";
TwoDim[3][2] = "X";
TwoDim[3][3] = "*";
TwoDim[3][4] = "X";
TwoDim[3][5] = "X";
TwoDim[4][0] = "*";
TwoDim[4][1] = "X";
TwoDim[4][2] = "*";
TwoDim[4][3] = "X";
TwoDim[4][4] = "*";
TwoDim[4][5] = "*";
TwoDim[5][0] = "*";
TwoDim[5][1] = "X";
TwoDim[5][2] = "*";
TwoDim[5][3] = "*";
TwoDim[5][4] = "*";
TwoDim[5][5] = "X";
TwoDim[6][0] = "X";
TwoDim[6][1] = "*";
TwoDim[6][2] = "*";
TwoDim[6][3] = "*";
TwoDim[6][4] = "X";
TwoDim[6][5] = "X";
TwoDim[7][0] = "*";
TwoDim[7][1] = "X";
TwoDim[7][2] = "*";
TwoDim[7][3] = "X";
TwoDim[7][4] = "X";
TwoDim[7][5] = "*";
TwoDim[8][0] = "X";
TwoDim[8][1] = "*";
TwoDim[8][2] = "X";
TwoDim[8][3] = "X";
TwoDim[8][4] = "*";
TwoDim[8][5] = "X";
TwoDim[9][0] = "*";
TwoDim[9][1] = "X";
TwoDim[9][2] = "*";
TwoDim[9][3] = "X";
TwoDim[9][4] = "X";
TwoDim[9][5] = "X";
TwoDim[10][0] = "*";
TwoDim[10][1] = "*";
TwoDim[10][2] = "X";
TwoDim[10][3] = "*";
TwoDim[10][4] = "X";
TwoDim[10][5] = "*";
TwoDim[11][0] = "*";
TwoDim[11][1] = "*";
TwoDim[11][2] = "X";
TwoDim[11][3] = "X";
TwoDim[11][4] = "*";
TwoDim[11][5] = "X";
TwoDim[12][0] = "*";
TwoDim[12][1] = "*";
TwoDim[12][2] = "*";
TwoDim[12][3] = "*";
TwoDim[12][4] = "X";
TwoDim[12][5] = "*";
for(int i = 0; i<13; i++){
    System.out.print("Row t");
    for(int j = 0; j <6; j++){
        System.out.print(TwoDim[i][j] + "t");
    }
    System.out.println();
}

更改线路

System.out.print("Row t");

类似的东西:

System.out.print("Row " + (i + 1) + "t");

好吧,i是你的行号,从0开始,所以只需写(假设你想从1开始(:

for(int i = 0; i<13; i++){
    System.out.print("Row t"+(i+1)+" ");
    for(int j = 0; j <6; j++){
        System.out.print(TwoDim[i][j] + "t");
    }
    System.out.println();
}
System.out.print("Row " + i +  "t");

i是数组中的第一个索引,因此对应于该行。如果要使索引基于1而不是基于0,请每次输出i + 1

不要使用行和列的硬编码值,使用以下代码:

    for(int i = 0; i<TwoDim.length; i++){   // Iterate to row count
        System.out.print("Row-"+(i+1)+"t"); // Change i to i+1
            for(int j = 0; j <TwoDim[i].length; j++){  // Iterate the column count
                System.out.print(TwoDim[i][j] + "t");
        }
        System.out.println();
    }

试试这个:

System.out.print("Row t"+i);

如果您的索引从1 开始

 System.out.print("Row t"+(i+1));

你试过了吗:

for(int i = 0; i<13; i++){
   System.out.print("Row t " + i);
   for(int j =0; j < 6; j++ {
       ...
   }
}

相关内容

  • 没有找到相关文章

最新更新