Reputation:
So I got this task to do : (Display patterns) Write a method to display a pattern as follows:
The method header is: public static void displayPattern(int n)
Basically , I understood "HOW" to do the excerice, and even coded it on my own and got 99% of the code right. I know that I need to do 2 loops, one that prints the whitespaces and each time declines by 1 and the other that prints the number after the whitespace and inclines by 1.
Here is my method:
public static void printPattern(int n) {
int m =1;
int k=1;
while (m-1-1 <=n) {
int numberOfWhiteSpaces = n -1;
for (int i = numberOfWhiteSpaces; i >= 0; i--) {
System.out.print(" ");
}
for (k=m; k>0; k--) {
System.out.print( k + "");
}
System.out.println();
m++;
n--;
}
}
Let's say i call
printPattern(3);
My only problem that the output is like this :
1
21
321
No white spaces between the numbers, and yes, I tried to change this:
System.out.print( k + "");
to this:
System.out.print( k + " ");
The result? :
I have been on this problem for 2 hours straight, couldn't get it right. Might use some help, thanks guys.
Upvotes: 4
Views: 608
Reputation: 726849
This happens because you did not count the number of spaces correctly: your code assumes that you need one space in the prefix portion of the string for each number that you print. However, when you switch to k + " "
, prefix would require two spaces, not one, per number printed (assuming single-digit numbers). Therefore, when you switch to k + " "
in the second loop, you need to also switch to System.out.print(" ");
(two space) in the first loop.
This will fix the problem for single-digit numbers. Generalizing to multi-digit numbers would require more work: you would need to count the number of digits on the last line, then count the number of digits on the current line, and print the required number of prefix spaces to compensate for the difference.
Upvotes: 6