Square display

The problem

Write a program that asks the user for a positive integer no greater than 15. The program should then draw a square on an output file using the character ‘X’. The number entered by the user will be the length of each side of the square. For example, if the user enters 5, the program should write the following to the output file:

XXXXX
XXXXX
XXXXX
XXXXX
XXXXX

If the user enters 8, the program should display the following:

XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX

Breaking it down

public static void main(String[] args) {

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    // Get a number from the user.
    System.out.print("Enter a number between 1-15: ");
    int number = keyboard.nextInt();

    //validate users input
    validateNumber(keyboard, number);

    //produce matrix
    outputMatrix("X", number);
    
    //close scanner
    keyboard.close();

}

/**
 * Method should validate a input number and continue to ask if the number
 * is now within range
 * 
 * @param keyboard
 * @param number
 */
static void validateNumber(Scanner keyboard, int number) {

    // Validate the input.
    while (number < 1 || number > 15) {
        // Get a number from the user.
        System.out.println("Sorry, that's an invalid number.");
        System.out.print("Enter an integer in the range of 1-15: ");
        number = keyboard.nextInt();
    }
}

/**
 * Method should output a row/column of char specified
 * 
 * @param charToOutput
 * @param number
 */
static void outputMatrix(String charToOutput, int number) {

    // display square made of char
    for (int row = 0; row < number; row++) {

        // display row
        for (int column = 0; column < number; column++) {
            System.out.print(charToOutput);
        }

        // Advance to the next line.
        System.out.println();
    }
}

Output

Enter a number between 1-15: 5
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX

Level Up

Modify the program to ask the user to enter a single character to produce the matrix. For example, if a user would enter a number of 8 and asterisk it would look like:

********
********
********
********
********
********
********
********