【问题标题】:Two dimensional array with 3x3 display具有 3x3 显示的二维阵列
【发布时间】:2018-03-24 23:39:03
【问题描述】:

我整个星期都在做这件事。是的,这是家庭作业,我意识到以前也有人问过同样的问题,但我无法使解决方案适用于我的特定代码。我需要让一个二维数组显示为3x3。我必须使用数组,它是赋值的一部分,它必须是3x3 并且有一个print 方法,所以这些不是我可以做的改变。

现在它们打印在一行中。这是我得到的结果:

如果你看不到截图,我得到的结果是:

第一个井字游戏:
X O X O O X X X O
第二个井字游戏:
O O X O O X X X O

这是我的代码:

public class tictactoe {
    public static void main(String[] args) {
        System.out.println("First Tic Tac Toe: ");
        char[][] ttt1 = { { 'X', 'O', 'X' }, { '0', 'O', 'X' }, { 'X', 'X', 'O' } };
        print(ttt1);

        System.out.println("Second Tic Tac Toe: ");
        char[][] ttt2 = { { 'O', 'O', 'X' }, { '0', 'O', 'X' }, { 'X', 'X', 'O' } };
        print(ttt2);
    }

    public static void print(char ttt1[][]) {
        for (char row = 0; row < ttt1.length; row++) {
            for (char column = 0; column < ttt1[row].length; column++)
                System.out.print(ttt1[row][column] + "     ");
        }
        System.out.println();
    }
}

【问题讨论】:

  • 没关系。您在提出格式良好且结构合理的问题方面做得很好。它包含一个演示问题、当前输出、所需输出和解释的小代码示例(比较How to Askminimal reproducible example)。干得好,请投我一票。
  • 顺便说一下,请遵守 Java 命名约定。类名应该是 CamelCase,所以TicTacToe。至少确保第一个字符是大写的。另外,如果我们调用static方法,我们通常会在前面添加类名作为标识符,这样大家就可以直接看到我们在调用static方法。所以在你的main 方法中应该是TicTacToe.print(ttt2);

标签: java arrays multidimensional-array


【解决方案1】:

打印出每一行后,您将缺少一个新行。

public static void print(char ttt1[][]) {
    for (char row = 0; row < ttt1.length; row++) {
        for (char column = 0; column < ttt1[row].length; column++)
            System.out.print(ttt1[row][column] + "     ");
        System.out.println();
    }
    System.out.println();
}

【讨论】:

  • 谢谢,我不敢相信它这么简单,但我并没有想到。绝对不会再犯这种错误了!非常感谢!
猜你喜欢
  • 2014-05-25
  • 1970-01-01
  • 2020-04-21
  • 2012-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
相关资源
最近更新 更多