I’m writing a program where I need to make a hollow box of asterixs’. The program works fine when I enter dimensions for a square but it doesn’t work when I enter dimensions for a rectangle.
import java.util.Scanner;
public class asterix {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
int stars; // length of side
int column; // width of box
int row = 1;
// prompt user to enter the length and width of box
System.out.print("Enter the length: ");
stars = input.nextInt();
System.out.print("Enter the width: ");
column = input.nextInt();
while ( row <= stars ) {
column = 1;
// and for as many columns as rows
while ( column <= stars ) {
if ( row == 1)
System.out.print( "*" );
else if ( row == stars )
System.out.print( "*" );
else if ( column == 1 )
System.out.print( "*" );
else if ( column == stars )
System.out.print( "*" );
else
System.out.print( " " );
column++; } // end inner while loop
System.out.println();
row++;
} // end output
} // end of main
} // end of Stars
The ideal output I would want is as follows:
Say its 3 by 3:
*** * * ***
and say its 4 by 3:
**** * * ****
You need to modify the following lines.
and
You compare both loops to the number of lines, and therefore get a square. You should use the number of columns in your inner-loop.
I’m sure it’s just a slip-up, you would have caught it.