Reputation: 123
I need to make a right aligned triangle using two methods:
This is as close as I can get:
public class Right {
private static void printStars(int k) {
for (int i = 0; i < k; i++) {
System.out.print("*");
}
System.out.println("");
}
private static void printSpaces(int k) {
for (int i = 0; i < k; i++) {
System.out.print(" ");
}
System.out.print("");
}
private static void printTriangle(int k) {
for (int i = 1; i <= k; i++) {
printSpaces(i);
printStars(i);
}
}
public static void main(String[] args) {
printTriangle(4);
}
}
I cannot get the space method to print in reverse...It just prints the same thing side by side, except one is just spaces.
*
**
***
****
Upvotes: 1
Views: 308
Reputation: 31269
For every line that you print, you're printing as many spaces as stars. But you want to right-align, so that can't be right.
What you want is the total number of characters on a line to be the same for every line, because you want to have the right side of the triangle be at the same location every line. So every line should be k
characters long, because that's the maximum amount of stars you're going to print.
And since you already know how many stars you want to print on every line, you have to subtract that from k
to find out how many spaces you need to print in front of it. So the number of spaces is k - i
(since the number of stars is i
).
So, change the invocation of printSpaces
and make it print k - i
spaces:
private static void printTriangle(int k) {
for (int i = 1; i <= k; i++) {
printSpaces(k - i);
printStars(i);
}
}
Upvotes: 2