# Drawing simple shapes using loops

• 05-29-2011, 06:49 AM
Quinn
Drawing simple shapes using loops
Hello all,
I have an assignment that I'm working on where I need to draw simple shapes using asteriks (*)
For example a square would be :
* * *
* * *
* * *
The length and width of the shape needs to be use inputed.
So far I have the loop working to print the required number of * horizontally but I can't figure out how to make it drop a line and reprint the horizontal *'s repeatedly until I have an X by X square. I think I need to use a nested loop but I can't seem to get it to work.
Here is what I have so far:
Code:

```import javax.swing.JOptionPane; public class A2Q1 {   public static void main(String[] args)   {     String inputString;    //For reading input     int sideLengthSquare;  //Length of side for square     int height = 1;         inputString = JOptionPane.showInputDialog("Enter the squares side length.");         sideLengthSquare = Integer.parseInt(inputString);         while (height <= sideLengthSquare)     {               if (height <= sideLengthSquare)         System.out.print ("* ");             else System.out.print ("\n");             height++;       }     }   }```
• 05-29-2011, 07:14 AM
pbrockway2
Quote:

I think I need to use a nested loop
Yes, you need to use nested loops rather than the single loop in the code you posted. Since you know how many times each loop will be repeated ahead of time (it's the number inputted by the user) for loops might be a good idea.
• 05-29-2011, 09:05 AM
JosAH
May I suggest the following three parameter method: the first parameter c is the char to be printed, the second parameter n is the number of times c is to be printed, the last boolean parameter eol tells the method whether or not to print a new line at the end:

Code:

```public static void printLine(char c, int n, boolean eol) {   for (int i= 0; i < n; i++)       System.out.print(c);   if (eol)       System.out.println(); }```
As an example, your square can be printed as follows:

Code:

```for (int line= 0; line < 3; line++)   printLine('*', 3, true);```
And many, many, more shapes can be printed by using a few loops and this little method.

kind regards,

Jos