简体   繁体   English

如何在不定义元素的情况下填充2D字符数组?

[英]How to populate a 2D array of characters without defining the elements?

I wish to make a 2D char array for a “robot arena” with the size being given. 我希望为“机器人竞技场”制作一个二维char数组,并给出其大小。

I have two functions, getY and getX that return (int) the x and y maximum coordinates of the arena, ie size 30 by 10, I want to make horizontal walls '-', vertical walls'|' 我有两个函数,getY和getX返回(整数)竞技场的x和y最大坐标,即30乘10,我想使水平墙为“-”,垂直墙为“ |” and diagonal walls at the 4 edges '/' for bottom right and top left corner, and '\\' for bottom left and top right corner. 和对角墙位于4个边缘的“ /”代表右下角和左上角,“ \\”代表左下角和右上角。 All other elements can be whitespace. 所有其他元素可以是空格。

I have tried using nested for loops but it just comes out wrong. 我尝试过使用嵌套的for循环,但结果是错误的。 Thank you 谢谢

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();
    }
  }
}

Output: 输出:

/--------\
|        |
|        |
|        |
|        |
|        |
|        |
|        |
|        |
\--------/

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

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