Skip to content

Instantly share code, notes, and snippets.

@klynton
Forked from objectsyndicate/Square.java
Last active December 10, 2015 17:08
Show Gist options
  • Save klynton/4465260 to your computer and use it in GitHub Desktop.
Save klynton/4465260 to your computer and use it in GitHub Desktop.
/**
* 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");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment