繁体   English   中英

尝试以数独样式打印2d数组

[英]Trying to print a 2d Array in a sudoku Style

所以我试图为Sudoku类做一个方法show()。 它使用(9x9)2d数组。 此方法以Sudoku样式显示打印数组,但我不确定如何实现。 我真的很感谢您的帮助。

我已经尝试过一些“ for循环”,但是正如我所说的,我真的不知道如何将数组分成3x3的正方形。 我只包含了一小部分代码。

公共无效的show()

{ 
    for(int[]row : values)
    {
        for(int value : row)
        {
            System.out.print(value);
            System.out.print("\t");
        }
        System.out.println();
    }
}

我需要的输出可能是这样的

0 0 0 | 0 0 0 | 0 0 0

0 0 0 | 0 0 0 | 0 0 0

0 0 0 | 0 0 0 | 0 0 0


0 0 0 | 0 0 0 | 0 0 0

0 0 0 | 0 0 0 | 0 0 0

0 0 0 | 0 0 0 | 0 0 0


0 0 0 | 0 0 0 | 0 0 0

0 0 0 | 0 0 0 | 0 0 0

0 0 0 | 0 0 0 | 0 0 0

当前输出:

0 0 0 8 5 9 3 0 0
5 0 4 3 2 0 8 0 0
0 0 3 0 0 7 0 9 0
0 4 5 1 0 0 0 0 0
2 7 8 0 0 0 9 1 6
0 0 0 0 0 8 4 2 0
0 3 0 6 0 0 2 0 0
0 0 1 0 9 3 6 0 7
0 0 2 7 8 5 0 0 0

如果仅在每行中缺少垂直线,则可以在该行中添加条件打印语句,因此在第二个和第六个元素之后添加一条垂直线。 也许像下面这样:

if(rowIndex == 2 || rowIndex == 5) {
    System.out.print("|");
}

编辑:要提及的一件事是,您将需要更改循环以跟踪您所在的索引。

请尝试以下操作:

for(int[]row:values)
    {
        for(int rowIndex = 0; rowIndex < row.length(); rowIndex++)
        {
            System.out.print(row[rowIndex]);
            System.out.print("\t");

            if(rowIndex == 2 || rowIndex == 5) {
                 System.out.print("|");
                 System.out.print("\t");
            }
        }
        System.out.println();
    }
}
public void show()
{ 
    for(int x = 0 ; x < 9 ; x++)
    {
        for(int y = 0 ; y < 9 ; y++)
        {
            System.out.print(values[x][y]);
            System.out.print("\t");
            if ((y + 1) % 3 == 0) {
                System.out.print("|\t");
            }
        }
        System.out.println();
        if ((x + 1) % 3 == 0) {
            System.out.println("----------------------");
        }
    }
}

暂无
暂无

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

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