Jan 8, 2018 at 8:38 pm Java

How to Create a Hollow Rectangle Using Asterisks in Java

A hollow rectangle such as the box shown below can be drawn by printing the star symbol on only the first and the last row, and the first and the last column.

We can fill the rest of the spaces, i.e. from row two up to the (last row – 1) and from column two up to the (last column – 1) with spaces to produce the hollow rectangle.

hollow box Java

 

Given the variable ‘size’ as the size of the row and the column: we can write the logic as follows:


for (int i=1; i<=size; i++){
   for(int j = 1; j<=size; j++){
       if(i==1 || i == size || j == 1 || j == size){
         System.out.print("*");
    }else {
      System.out.print(" ");
   }
 }
 System.out.println(); //Jump to the next row
 }

Here is the full code:


/** This program prints a hollow box using  the asterisk symbol (*) using
  * the size given by the user
**/
import java.util.*; //We need to import it to use the Scanner class
public class HollowBox{
    public static void hollowBox(int size){
	for (int i=1; i<=size; i++){
	   for(int j = 1; j<=size; j++){
	       if(i==1 || i == size || j == 1 || j == size){
		  System.out.print("*");
		}else {
		    System.out.print(" ");
		}
	    }
	    System.out.println(); //Jump to the next row
	}
   }
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.println("Please enter a size");
      int size = input.nextInt();
      hollowBox(size);
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *