Reputation: 131
When I am running this program in eclipse I am getting the output that shows a rectangle with 5 stars in a column and 5 stars in a row. It should be 5 stars in a column and 2 stars as row. What's wrong with my code?
public class printing {
public static void main(String[] args) {
// printStars(5);
// printStars(3);
// printStars(9);
// printStars(4);
// printSqare(4);
printRectangle(5,2);
}
private static void printStars(int amount) {
int i = 0;
while ( i < amount ) {
System.out.print("*");
i++;
}
System.out.println("\n");
}
// private static void printSqare(int sidesize){
// int c= 0;
// while (c < sidesize){
// printStars(sidesize);
// c++;
// }
// System.out.println("\n");
// }
private static void printRectangle(int width, int height) {
int num1=0;
for (int num2=1; num2<height; num2++){
while (num1 < width ){
printStars(width);
num1++;
}
}
}
}
Upvotes: 1
Views: 452
Reputation: 3844
You can change your printRectangle method like
private static void printRectangle(int width, int height) {
for (int num2 = 0; num2 < height; num2++) {
printStars(width);
}
}
I read your question as having 5*2 rectangle. Not sure if its correct interpretation though.
Upvotes: 0
Reputation: 5140
Your commented printSquare
method is actually good, you can reuse the algorithm for printRectangle
!
You need only one loop here, so
private static void printRectangle(int width, int height) {
int num1=0;
while (num1 < height ){
printStars(width);
num1++;
}
}
or
private static void printRectangle(int width, int height) {
for (int num1 = 0; num1 < height; num1++ ){
printStars(width);
}
}
In you current code, you enter in the for
loop, and then call printStars
in your while
loop. However, while
loops 5 times instead of 2, because of the condition num1 < width
(instead num1 < height
). Then, for
loops a second time and do nothing (because num1
is greater than width
).
Upvotes: 4