Technically it has been more than a month but for the last month, while I’ve been recovering from my surgery and getting sick every 2 weeks I’ve been stuck on a Java program that we were assigned. So it is technically really late, however, medical needs, yadda yadda means it’s not. I’ve finally got it working and I want to, now, share the solution so that if anyone else runs into trouble they can at least use my code for a reference since the rest of the code out there is utter shit.
Here’s the program I wrote, it includes the prompt for the question and a note from my Professor. The book is How to Program Java, Late Objects Version by Deitel:
/** * Do problem 3.29 from the book, but call your program Square.java. The text * for this question is: * Write an application that prompts the user to enter the size of the side of * a square, then displays a hollow square of that size made of asterisks. Your * program should work for squares of all side lengths between 1 and 20. * * A Note From Dr. B. * There are 3 parts to this problem. The first is the top row of stars. After * you have code that prints the top row of stars correctly, focus on printing * 1 star, then the correct number of spaces, * then the closing star. Once * you can print that correctly, wrap that code inside a while loop so * that you get the correct number of rows with stars at both ends. Finally, * you can print the last row of complete stars. * * @author Klynton Jessup * @version 2011-03-08 * */
import java.util.Scanner;
public class Square{ public static void main (String[] args) { //First, declare variables. int x; int s; int p; int r = 0; int y = 1; int z = 1; int f = 1; Scanner input = new Scanner(System.in); //Next, ask for and get 'input' variables from the user System.out.printf("Please enter an integer: "); x = input.nextInt(); //Next, compute the desired result, store in 'output' variables. s = x + 2; p = x - 2; //Finally, print the results to the console window. while (y <= x) { System.out.printf(" * "); y++; } while (r < p) { System.out.print("\n * "); while (z <= p) { System.out.print(" "); z++; } System.out.print(" * "); r++; z=1; } System.out.print("\n"); if (x > 1) { while (f <= x) { System.out.printf(" * "); f++; } System.out.printf("\n"); } else System.out.printf("\n"); }}So that’s my solution for printing a hollow box in Java when you want the perimeter of the box to be a specific size. Here’s some SEO nonsense so people actually find this, print a square in java, print a hollow square in java, java print a square, java print a hollow square. (I don’t normally do that nonsense but rather than someone else spending a bunch of time on this they can get here.)
Here’s a sample of the program output:
