繁体   English   中英

我正在尝试将char的2d数组初始化为空格,但是控制台中的输出很奇怪

[英]I'm trying to initialize a 2d array of char into spaces, but the output in the console is weird

以下是我的构造函数,我尝试使用spaces初始化数组,但是当我打印出*作为边框(在我的toString中)时,奇怪的是控制台中的输出

// constructs a screen based on the dimensions
public Screen(int height, int width) {
    screen = new char[height+2][width+2];
    for (int i = 0; i < screen.length; i++) {
        for (int j = 0; j < screen[i].length; j++) {
            screen[i][j] = ' ';
        }
    }
}

输出低于


*
Ū
ʪ
Ϫ
Ԫ

ު


୪୪୪୪୪୪୪୪୪୪୪

我构造了一个9 x 9屏幕,我不知道哪里出了问题。

public String toString() {
    String str = "";
    for (int row = 0; row < screen.length; row++) {
        for (int col = 0; col < screen[row].length; col++) {
            if (row == 0 || col == 0 || row == screen.length-1) {
                str += border;
            } else {
                border += screen[row][col];
            }
        }
        str += "\n";
    }
    return str;
}

您的toString看起来很奇怪。

你写了 :

if (row == 0 || col == 0 || row == screen.length-1) {
    str += border;
} else {
    border += screen[row][col];
}

应该是: str += screen[row][col];



更好的解决方案

尽管如此,以前的解决方案仍然可以使用,我建议您采用这种方式:

public static class Screen {
    private char[][] screen;
    private static final String BORDER = "*";

    public Screen(int height, int width) {
        screen = new char[height][width];
        for (int i = 0; i < screen.length; i++) {
            for (int j = 0; j < screen[i].length; j++) {
                screen[i][j] = ' ';
            }
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        // add (screen.length + 2) for the first line.
        for (int i = 0; i < screen.length + 2; i++) {
            sb.append(BORDER);
        }
        sb.append(System.getProperty("line.separator"));

        for (int i = 0; i < screen.length; i++) {
            // star at the begin of each line
            sb.append(BORDER);
            for (int j = 0; j < screen[i].length; j++) {
                sb.append(screen[i][j]);
            }
            // star at the end of each line
            sb.append(BORDER);
            sb.append(System.getProperty("line.separator"));
        }

        // add (screen.length + 2) for the last line.
        for (int i = 0; i < screen.length + 2; i++) {
            sb.append(BORDER);
        }

        return sb.toString();
    }
}

通过这种方式打印墙阵列,您不会覆盖边框内容。 (在数组周围添加星号,而不是边框

暂无
暂无

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

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