Advertisement
advictoriam

Untitled

Jan 20th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class SquareBoard
  4. {
  5.    private String[][] board;
  6.    private int length;
  7.  
  8.    /**
  9.       Constructs an empty square game board.
  10.       @param sideLength the length of each side
  11.    */
  12.    public SquareBoard(int sideLength)
  13.    {
  14.       length = sideLength;
  15.       board = new String[length][length];
  16.       // Fill with spaces
  17.       for (int i = 0; i < length; i++)
  18.          for (int j = 0; j < length; j++)
  19.             board[i][j] = " ";
  20.    }
  21.  
  22.    /**
  23.       Creates a string representation of the board, such as
  24.       |x o|
  25.       | x |
  26.       | o |.
  27.       @return the string representation
  28.    */
  29.    public String toString()
  30.    {
  31.       String r = "";
  32.       for (int i = 0; i < length; i++)
  33.       {
  34.          r = r + "|";
  35.          for (int j = 0; j < length; j++)
  36.             r = r + board[i][j];
  37.          r = r + "|\n";
  38.       }
  39.       return r;
  40.    }  
  41.  
  42.    /**
  43.       Fills the diagonals of this square board with "*" strings.
  44.    */
  45.    public void fillDiagonals()
  46.    {
  47.       for(int i = 0; i < length; i++)
  48.       {
  49.          for(int j = 0; j < length; j++)
  50.          {
  51.             if(j == i || length - i - 1 == j)
  52.             {
  53.                board[i][j] = "*";
  54.             }
  55.             else
  56.             {
  57.                board[i][j] = " ";
  58.             }
  59.          }
  60.       }
  61.    }
  62.    
  63.    // This method is used to check your work.
  64.  
  65.    public static void main(String[] args)
  66.    {
  67.       Scanner in = new Scanner(System.in);
  68.       int n = in.nextInt();  
  69.       SquareBoard board = new SquareBoard(n);
  70.       board.fillDiagonals();
  71.       System.out.println(board.toString());
  72.    }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement