# Thread: Drawing simple shapes using loops

1. Member
Join Date
May 2011
Posts
5
Rep Power
0

## 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:
Java Code:
```import javax.swing.JOptionPane;

public class A2Q1
{
public static void main(String[] args)
{
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++;
}
}
}```

2. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,717
Rep Power
16
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.

3. 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:

Java 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:

Java 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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•