尝试以数独风格打印二维数组

Trying to print a 2d Array in a sudoku Style

所以我正在尝试为数独 class 做一个方法 show()。它使用 (9x9)2d 数组。此方法显示以数独样式打印数组,但我不确定如何实现它。非常感谢您的帮助。

我已经尝试了一些 "for loops" 但正如我所说,我真的不知道如何将数组分隔成 3x3 方格。我包含了一小部分代码。

public void 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("----------------------");
        }
    }
}