Create a Square of stars with an inputed number

638 views Asked by At

I need a code to help me print a square of stars with an Integer input (in this case the number is 5) the square must be empty on the inside.

for example:

Looking for this output

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

what I get

* * * * 
*       
*      
*       
* * * * 

I am missing my right side of the square.

MY code:

    System.out.print("Please enter a number: ");
    side = input.nextInt();
    for (int i = 0; i < side - 1; i++) {
        System.out.print("* ");

    }
    for (int i = 0; i < side; i++) {
        System.out.println("*");
    }
        
    for (int i = 0; i < side; i++) {
        System.out.print("* ");

    }

}

input

5

output

* * * * 
*       
*      
*       
* * * * 
3

There are 3 answers

1
Thiyagu On BEST ANSWER

You can do this with a nested for loop.

for (int i = 0; i < side; i++) {
    for (int j = 0; j < side; j++) {
        if (i == 0 || i == side - 1 || j == 0 || j == side - 1) {
            System.out.print("* ");
        } else {
            System.out.print("  ");
        }
    }
    System.out.println();
}

Print a * if it is either first row/column or last row/column; otherwise print two spaces.

5
Thomas M On

You need to add an extra star at the end of the middle for loop. This can be done by nested a second for loop of spaces followed by printing the star.

for (int i = 0; i < side; i++) {
    System.out.print("*");
    for (int j = 0; j < side; j++) {
        System.out.print("  ");
    }
    System.out.println("*");
}
1
Amit Kumar Lal On

It can be done using a single For Loop with a Complexity of O(n)

public static void main(String[] args) {
    System.out.print("Please Enter a Number ");
    Scanner scanner = new Scanner(System.in);
    int number = scanner.nextInt();
    if(number >= 3) {
        String endPattern = new String(new char[number]).replace("\0", " *");
        String midPattern = String.format("%-"+(number-2)*2+"s  %s", " *"," *");
        
        for(int i=1; i<= number; i++) {
            if(i==1 || i==number) {             
                System.out.print(endPattern);
            }
            else {
                System.out.print(midPattern);
            }
            System.out.println();
        }
    }
}

Output (for input 3)

Please Enter a Number 3
 * * *
 *   *
 * * *

output (for input 7)

Please Enter a Number 7
 * * * * * * *
 *           *
 *           *
 *           *
 *           *
 *           *
 * * * * * * *