Basically, I am trying to print lines of characters, specifically asterisks. Every subsequent line should have one less asterisk than the previous line. Additionally, they should all be aligned to the right . My knowledge of Java is not too strong, so bear with me.
Here's an image of the output and the instructions:
Let's start off with a simpler example:
***
**
*
What pattern do you see? The pattern is that on each line, the sum of the amount of asterisks and the amount of spaces is constant. I'll call this constant L
for now on, which stands of the line length .
From this, we can infer that amountOfSpaces
is L - amountOfAsterisks
, and vice versa (as the magical laws of Algebra also apply here).
So from this, we can deduce that on each line we need to print L - amountOfAsterisks
spaces first, and then amountOfAsterisks
. For cases like these, for
loops are a life-saver (In more professional code (as professional as you can get with fancy terminal graphics) this would be done a bit differently, as in actuality using for
-loops for such a thing makes the function O(N)
).
The rest is up to you
Can modify the variables as you see fit. Key is to use a bunch of for loops and keep track of all the variables.
for (int i = 0; i < 8; i++) { //line number your on
for(int k = 0; k<i;k++)//keeps track of number of spaces to use, line number minus 1 spaces printed
{
System.out.print(" ");
}
for (int j = 8; j >i; j--) {//prints out 8 * and reduced by 1*line number
System.out.print("*");
}
System.out.println();//prints new line and initiates new line by i++
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.