首页 > 解决方案 > 如何创建具有二维数组的矩形?

问题描述

在这个练习中,我们必须使用从 10 到 15 行和 20 到 30 列的二维数组绘制一个矩形,将矩形“#”的边框放入矩形“-”内。它必须看起来像这样:https ://i.stack.imgur.com/IOqY6.png

到目前为止我的代码是这样的,但我需要一些帮助来修复它,因为我对这个练习有点迷失:

public class Practica9{
public static void main(String[] args){

    char [][] tablero = new char [10][20];
    for (int i = 0; i < 10; i++){   
        for (int j = 0; j < 20; j++){
            tablero [0][19] = #;
            tablero [9][19] = #;
            System.out.println (tablero[0][19]);
            System.out.println (tablero[9][19]);
        }
    }
    for (int i = 0; i < 10; i++){
        for (int j = 0; j < 20; j++){
            tablero [1][18] = -;
            tablero [8][18] = -;
            System.out.println (tablero [1][18]);
            System.out.println (tablero [8][18]);
        }
    }
}
}

标签: javaarraysmultidimensional-arrayrectanglesdrawrectangle

解决方案


public static void main(String[] args){
      int rows = 15;
      int columns =30;
      char [][] rectangle = new char[rows][columns];
      // fill array
      for(int i = 0; i < rows; i++){
            for(int j = 0; j < columns; j++){
                  if(i==0 || j==0  || i==rows-1 || j==columns-1){
                          rectangle[i][j] = '#';
                  }
                  else{
                           rectangle[i][j] = '-';
                  }
            }
      }
     // print array
      for(int i = 0; i < rows; i++){
            for(int j = 0; j < columns; j++){
                  System.out.print(rectangle[i][j]);
            }
           System.out.println();
      }
}

推荐阅读