My problem is with the very centre while loop. The goal of the program is to print a box made of asterisks with the specified dimensions provided by the user, and it works fairly well. However, the centre while loop will not print the white spaces to distance itself.
What could be causing this?
import java.util.Scanner;
public class bonus {
/**
* @param args
*/
public static void main(String[] args) {
Scanner widthScan = new Scanner(System.in);
System.out.println("Enter the width: ");
int width = widthScan.nextInt();
Scanner heightScan = new Scanner(System.in);
System.out.println("Enter the height: ");
int height = heightScan.nextInt();
int resetWidth = width;
///////////////////////////////////////////////////////////opening width sandwich
while(width>=1)
{
System.out.print("*");
width--;
}
System.out.println();
///////////////////////////////////////////////////////////
int specialHeight = height-2;
int specialWidth = width-2;
while(specialHeight>=1)
{
System.out.print("*");
while(specialWidth>=1)
{
System.out.println(" ");
specialWidth--;
}
System.out.print("*");
specialHeight--;
System.out.println();
}
////////////////////////////////////////////////////////////
while(resetWidth>=1)
{
System.out.print("*");
resetWidth--;
}
////////////////////////////////////////////////////////////closing width sandwich
}
}
After this loop:
while(width>=1)
width
is clearly 0 or less.
Next you do:
int specialWidth = width-2;
So specialWidth
is -2 or less.
You then have:
while(specialWidth>=1)
How would you expect to ever enter that loop? What do you expect specialWidth
to be? It's not clear how you intended specialWidth
to be initialized (perhaps the initial value of width
?) but that's probably the place to look.
Now would also be a good time to learn to use a debugger, so you can step through the code to work out what's going on, if you can't do it by inspection.
See more on this question at Stackoverflow