简体   繁体   English

使用二维数组的Java控制台输出

[英]Java console output using two dimensional arrays

I'm looking for insight as to how to print two dimensional arrays from left to right as opposed to cascading down the page with newline characters. 我正在寻找有关如何从左到右打印二维数组的见识,而不是在页面上用换行符层叠。

I've written a simple program for an undergraduate AI course that solves that little 9-tile games. 我已经为一个大学的AI课程编写了一个简单的程序,可以解决9小块游戏。

public void printNode(){
    for(int i = 0; i < 3; i ++){
        System.out.printf("[ ");
        for(int k = 0; k < 3; k++){
            System.out.printf(" " + state[i][k] + " ");
        }
        System.out.printf("]\n");
    }
}

This prints the two dimensional array with no problems. 这样就可以毫无问题地打印二维数组。

But I'm looking for a way to print the arrays from left to right so I don't have to turn in 50+ pages of transformations to prove my program works. 但是我正在寻找一种从左到右打印数组的方法,因此我不必上交50多页的转换即可证明我的程序有效。 Has anyone solved this problem before? 有人解决过这个问题吗?

[ 1 2 3 ] [1 2 3]
[ 8 0 4 ] [8 0 4]
[ 7 6 5 ] [7 6 5]

This is the effect I want to create. 这是我要创建的效果。 The solution path of transformations is a series of pointers leading back up the chain. 转换的解决方案路径是一系列指向链上的指针。 Each of my Node's has a pointer to its ancestor. 我的每个Node都有一个指向其祖先的指针。 So I can easily follow the pointers back and print them all. 因此,我可以轻松地将指针向后移动并全部打印出来。

I'm not going to get into implementation details here, but here's some steps you can take 我不会在这里详细介绍实现细节,但是您可以按照以下步骤进行操作

  • print all of the top rows of every matrix, so you'll have a string like 打印每个矩阵的所有顶部行,因此您将得到一个类似

[ 1 2 3 ] [1 2 3] [1 2 3] [1 2 3]

  • add a newline, and print the next row of all the matricies. 添加换行符,然后打印所有矩阵的下一行。

[ 1 2 3 ] [1 2 3] [1 2 3] [1 2 3]
[ 8 0 4 ] [8 0 4] [8 0 4] [8 0 4]

  • continue until entire matrix is printed. 继续直到打印完整个矩阵。

[ 1 2 3 ] [1 2 3] [1 2 3] [1 2 3]
[ 8 0 4 ] [8 0 4] [8 0 4] [8 0 4]
[ 7 6 5 ] [7 6 5] [7 6 5] [7 6 5]

essentially you iterate through each matrix equal to their heights. 本质上,您迭代每个等于其高度的矩阵。 If they have different heights, you can start skipping the shorter ones, and just leave a blank space in it's place. 如果它们的高度不同,则可以开始跳过较短的高度,而只需在其位置留一个空白。

public void printTwoNodes(int arr[], int arr2[]){
    for(int i = 0; i < 3; i ++){
        System.out.printf("[ ");
        for(int k = 0; k < 3; k++){
            System.out.printf("" + arr[i][k] + " ");
        }
        System.out.printf("]");
        System.out.printf("[ ");
        for(int j = 0; j < 3; j++){
            System.out.printf("" + arr2[i][j] + " ");
        }
        System.out.printf("]\n");
    }
}

Can and should be improved 可以而且应该改进

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

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