hi i would like to draw a square with * as an outline and dot in the middle with size range 4 -20.
*****
*...*
*...*
*...*
*****
i’m having a trouble to make the height equal with the length.
this is my code, could you please help.. thanks
class Main
{
public static void printSquare( int size )
{
if ( size >= 20 && size >= 4)
{ size = 4; }
int squareLenght = size;
int i = 1;
int p = 1;
if ( p <= size )
{
int t = 1;
while ( t <= squareLenght )
{
System.out.print( "*" );
t = t + 1;
}
}
System.out.println(); // Newline
i = i + 1;
while ( i <= squareLenght )
{
int d = 1;
int s = 1;
if ( s < squareLenght );{
System.out.print( "*" );
s = s + 1;
}
while ( d < size-1 )
{
System.out.print( "." );
d = d + 1;
}
System.out.println( "*" );
i = i + 1;
}
if ( p <= size )
{
int t = 1;
while ( t <= squareLenght )
{
System.out.print( "*" );
t = t + 1;
}
}
System.out.println();
i = i + 1;
}
}
You’re printing 1 too many lines in the body (in between the borders) because of this line:
while ( i <= squareLenght )It should be
while ( i < squareLenght)ORwhile ( i <= squareLenght - 1 )since there should be 2 borders andsize - 2rows in the middle that make up the height.Also, this doesn’t make any sense:
Perhaps for the range you want:
Anyway your code’s a bit of a mess with unnecessary
ifstatements and just the whole structure of things.forloops would also be a good idea where you havewhileloops with an initialization, a condition and a modifier/increment. I’m not going to change it for you because it sounds like homework.Anyway if you wanted to neaten it up, think about the actual structure and pattern of what you’re doing, because it’s fairly simple:
sizeamount of asterisks ('*') and a new line (top border)size - 2times: (ifsizeis 5, there are 3 lines in between the borders, ie.size - 2)'*''.'size - 2times'*'sizeamount of asterisks ('*') and a new line (bottom border)EDIT: I know you’ve already marked the question as answered, but just wanted to suggest you have a function like
printRepeatedly(char c, int count)to reduce the amount of loops that you’re repeating (it’ll just be aforloop and a print statement).I just rewrote your code and I only required 11 lines of code in
printSquare, plus the 2 inprintRepeatedly). If you’re going to repeat code you should nearly always use functions/methods instead.