patternjavaMinor
Making a rectangular-shaped pattern
Viewed 0 times
patternshapedmakingrectangular
Problem
I'd like someone to suggest a better way to create this pattern in Java which I'm sure is possible:
I'm working my way through a new Java book and am examining string patterns.
Off the top of my head, I'd say that I could replace the values in the loops with constants to work towards. For example:
Any thoughts?
*********
* *
* *
* *
* *
* *
* *
* *
*********I'm working my way through a new Java book and am examining string patterns.
public static void drawRectangle() {
// y axis
for( int y = 0; y <= 8; y++ )
{
if( y == 0 || y == 8 )
{
System.out.print( "*********\n" );
if( y == 8 )
{
// Leave loop
break;
}
}
// x axis
for( int x = 0; x <= 8; x++ )
{
if( x == 0 || x == 8 )
{
System.out.print( "*" );
if( x == 8 )
{
System.out.println();
}
}
else
{
System.out.print( " " );
}
}
}
}Off the top of my head, I'd say that I could replace the values in the loops with constants to work towards. For example:
final static int END_POINT = 8;Any thoughts?
Solution
It's ok for a first iteration.
- But your 2nd iteration should be
drawRectangle(int width, int height). That will force you to not hard-code your numbers.
- Your 3rd iteration should be noticing that your rectangle only has 2 different rows (one row fills up the width with and the other only has in the beginning and end). You might want to make a method
drawHorizontalto draw the top and bottom anddrawEndsto draw the sides. For example
void drawHorizontal(int width) {
for (int i=0 ; i<width ; i++) {
System.out.print("*"); /* notice I'm using print() not println() */
}
System.out.println(""); /* notice I'm using println() */
}
void drawEnds(int width) {
System.out.print("*");
for (int i=1 ; i<width-1 ; i++) {
System.out.print(" ");
}
System.out.println("*");
}Code Snippets
void drawHorizontal(int width) {
for (int i=0 ; i<width ; i++) {
System.out.print("*"); /* notice I'm using print() not println() */
}
System.out.println(""); /* notice I'm using println() */
}
void drawEnds(int width) {
System.out.print("*");
for (int i=1 ; i<width-1 ; i++) {
System.out.print(" ");
}
System.out.println("*");
}Context
StackExchange Code Review Q#31379, answer score: 9
Revisions (0)
No revisions yet.