【问题标题】:Is there a way to print interspersed rows of 2d arrays?有没有办法打印散布的二维数组行?
【发布时间】:2021-08-16 04:47:47
【问题描述】:

所以,我想打印第一个数字数组的第一行,然后在下一行打印第二个数组(字符串数组)的第一行,依此类推。

有没有办法做到这一点?

这是我的代码:

for (int i = 0; i<=7 ; i++) {
    for (int j = 0; j <=7 ; j++) {
        System.out.print("|  "+MatrizNumeros[i][j]+"  |");
        System.out.print(" ");
    }
    System.out.println(" ");
    for (int k = 0; k <=7 ; k++) {
        System.out.print("|  "+MatrizCaracteres[i][k]+"  |");
        System.out.print(" ");
    }
}

我希望输出看起来像这样:

印刷应该是怎样的:

【问题讨论】:

  • 你能分享一些输入数据吗?输出应该是什么,因为我没有得到你想要的这个二维数组?你想打印第一个元素还是什么?

标签: java arrays printing


【解决方案1】:

您的代码一目了然,您只需要在值之前添加填充,并在每个循环周期之后添加格式。

一个很好的方法是创建一个添加填充的方法,这将有助于避免重复代码:

public void printArrayLine(String[][] array, int row){
    //Value for padding (7 characters)
    int padding = 7;
    //Loop through the row
    for (int x = 0; x < array.length; x++) {
        //Get value
        String value = array[row][x];
        //Calculate padding
        String padding = " ".repeat(padding - value.length());
        //Print pipe, padding and value
        System.out.print("|" + padding + value);
    }
    //Add a "|" the the end of the line and advance to the next line by adding a line separator
    System.out.print("|" + System.getProperty("line.separator"));
}

你可以使用这样的方法:

for (int i = 0; i<=7 ; i++) {
    //print a line of dashes "---"
    System.out.print("-".repeat(57));
    //Print a row from each array
    printArrayLine(MatrizNumeros, i);
    printArrayLine(MatrizCaracteres, i);
}
//print the final line of dashes "---"
System.out.print("-".repeat(57));

结果应该与您在任何使用单一字体的控制台中的图像相似。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多