试图在一个数独样式打印二维数组

问题描述 投票:0回答:2

所以我试图做的方法秀()的数独类。它采用了(9×9)2D阵列。这种方法显示打印数独的风格数组,但我不知道如何实现它。我真的很感激一些帮助。

我心中已经已经尝试了一些“for循环”但我说我真的不知道如何到阵列中的3×3平方分开。心中已经包括在代码的一小部分。

公共无效显示()

{ 
    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

java multidimensional-array printing sudoku
2个回答
1
投票

如果你只缺少每一行的垂直线,可以在该行添加条件打印语句,所以第二和第六元素后添加一条垂直线。也许类似如下:

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

1
投票
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("----------------------");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.