Creating a hollow shape using nested for loops (Java)

Viewed 53

The goal is to create a program where it will print a hollow shape. The user input will be the number of hollow shapes in a square.

I made this program where this should be the output. 1 2 3

As of now. this program can give the right output if the input is less than or equal to 6. Any idea how can I make this limitless?

package tester;

import java.util.Scanner;

public class Tester {


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int ui, sideL;

        System.out.println("(Note: The number should be greater than or equal to 1: ");
        System.out.println("Enter a number: ");

        ui = input.nextInt();

        sideL = (ui * (ui - 1)) + 1;

        if (ui >= 1) {

            for (int a = 1; a <= sideL; a++) {
                for (int b = 1; b <= sideL; b++) {
                    if (a == 1 ||
                        b == 1 ||
                        a == ui ||
                        b == ui ||
                        a == sideL ||
                        b == sideL ||
                        a == ui + (ui - 1) ||
                        b == ui + (ui - 1) ||
                        a == ui - 1 + (ui + (ui - 1)) ||
                        b == ui - 1 + (ui + (ui - 1)) ||
                        a == ui - 1 + (ui - 1 + (ui + (ui - 1))) ||
                        b == ui - 1 + (ui - 1 + (ui + (ui - 1))) ||
                        a == ui - 1 + (ui - 1 + (ui - 1 + (ui + (ui - 1)))) ||
                        b == ui - 1 + (ui - 1 + (ui - 1 + (ui + (ui - 1))))) {

                        System.out.print("* ");

                    } else {
                        System.out.print("  ");
                    }
                }
                System.out.println();
            }
        } else {
            System.out.println("Invalid input!");
        }
    }
} 
0 Answers
Related