![](/img/trans.png)
[英]How could I read Java Console Output into a 2d n*m double matrix/array
[英]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.