Skip to content

Instantly share code, notes, and snippets.

@csabatini
Created February 14, 2014 02:43
Show Gist options
  • Save csabatini/8994911 to your computer and use it in GitHub Desktop.
Save csabatini/8994911 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
import java.util.Arrays;
public class Square {
public static void drawSquare(int dim) {
// Create an array with one string element to contain each row
String arr[] = new String[dim];
Arrays.fill(arr, "");
System.out.println("Your square: ");
// Populate the row strings with asterisks
for (int i = 0; i < dim; i++) {
// First or last row?
if (i == 0 || i == dim-1) {
for (int j = 0; j < dim; j++)
arr[i] += "* ";
} else { // Middle rows
for (int k = 0; k < (dim-1)*2 + 1; k++) {
if (k == 0 || k == (dim-1)*2)
arr[i] += "*";
else
arr[i] += " ";
}
}
}
// Print out the strings
for (int z = 0; z < arr.length; z++)
System.out.println(arr[z]);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean valid = false;
int dim = 0;
while (!valid) {
try {
System.out.print("Enter " +
"the side length of the square to draw: ");
dim = input.nextInt();
valid = true;
} catch (Exception e) {
System.out.println("Not valid, try again.");
input.next();
}
}
drawSquare(dim);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment