【问题标题】:I need to print a two dimensional char array我需要打印一个二维字符数组
【发布时间】:2022-11-16 21:41:52
【问题描述】:

我需要创建一个棋盘游戏和 output of the array needs to look like this

But the output of my code looks like this:

我怎样才能摆脱这些标志并使其看起来像我需要的输出?

这是我的代码:

private char[][] boardMatrix;

    public TryingSth() {
        boardMatrix = new char[3][3];
//        boardMatrix[0][0] = 'H';

        for (int i = 0; i < boardMatrix.length; i++) {
            for (int j = 0; j < boardMatrix.length; j++) {
                if (i==0 && j==0){
                    System.out.print('H');
                } else if (i ==2 && j==2){
                    System.out.print('G');
                }else
                boardMatrix[i][j] = '_';
                System.out.print(boardMatrix[i][j] + " ");
            }
            System.out.println();
        }
    }

【问题讨论】:

  • 第一步是编写可以编译的代码。除了您的方法缺少返回类型(以及命名约定的忽略)之外,您的代码完全按照它应该做的去做
  • 但是为什么不将 G 和 H 存储在那个 boardMatrix 中呢?

标签: java arrays multidimensional-array


【解决方案1】:

您在每次循环迭代时打印 boardMatrix[i][j]。然而,如果你仔细观察,你会发现你设置boardMatrix[i][j]的值仅当它等于_ 时。因此当你想打印'H'或'G'时,boardMatrix[i][j]的值没有初始化,只是一些随机字节,所以这个字符被打印成一个划线框(带有这个代码的字符是不可打印的) .

您需要将 System.out.print('H');System.out.print(G'); 相应地更改为 boardMatrix[i][j] = 'H';boardMatrix[i][j] = 'G';

【讨论】:

  • 我怎么没想到呢?非常感谢您的帮助。欣赏它
猜你喜欢
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 2019-04-19
  • 2016-02-15
  • 2020-02-25
  • 1970-01-01
相关资源
最近更新 更多