【问题标题】:How to populate a 2D array of characters without defining the elements?如何在不定义元素的情况下填充二维字符数组?
【发布时间】:2018-04-11 22:41:16
【问题描述】:
我希望为“机器人竞技场”制作一个 2D 字符数组,其大小已给定。
我有两个函数,getY 和 getX,它们返回(int)竞技场的 x 和 y 最大坐标,即大小为 30 x 10,我想制作水平墙'-',垂直墙'|'和对角墙在 4 条边上,“/”表示右下角和左上角,“\”表示左下角和右上角。所有其他元素都可以是空格。
我曾尝试使用嵌套的 for 循环,但结果是错误的。谢谢
【问题讨论】:
标签:
java
arrays
eclipse
multidimensional-array
【解决方案1】:
public class GenerateBoard {
public static void main(String[] args)
{
int xRow = 10;
int yCol = 10;
char[][] board = new char [xRow][yCol];
for(int x = 0; x < xRow; x++) {
for(int y = 0; y < yCol; y++) {
if (x == 0 || x==(xRow-1)) // Sets top and bottom rows to -
board[x][y] = '-';
else if (y == 0 || y==(yCol-1)) // Sets left and right rows to |
board[x][y] = '|';
else
board[x][y] = ' '; // Fills other spaces with ' '
}
}
board[0][0] = '/'; //Top left
board[0][yCol-1] = '\\'; //Bottom Left
board[xRow-1][0] = '\\'; //Top right
board[xRow-1][yCol-1] = '/'; //Bottom Right
//Print Board
for(int x = 0; x < xRow; x++) {
for(int y = 0; y < yCol; y++) {
System.out.print(board[x][y]);
}
System.out.println();
}
}
}
输出:
/--------\
| |
| |
| |
| |
| |
| |
| |
| |
\--------/