问题
I have modified sample code around to get the output I was looking for, but I do not understand the logic behind the nested for-loops below. Can someone explain to me in detail what each loop is doing and why is are the loops constructed in this way?
public class Pyramid {
public static void main(String[] args) {
int size = 15;
for (int i = 1; i <= size; i += 2) {
for (int k = 0; k < (7 - i / 2); k++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
output (below):
*
***
*****
*******
*********
***********
*************
***************
回答1:
Nested for loops like that are used when you have pseudo code like this:
Do the following x times:
Do the following y times:
some stuff
Do the following z times:
some stuff
In your specific case, the size of the pyramid is dynamic and is stored in a variable called size
. To print a pyramid, you have to print size
times the following thing:
- Some whitespace and some
*
How do you print that then? You calculate how many white spaces and *
should there be and print them. Since the numbers of whitespaces and *
are dynamic, you need a for loop to do this, instead of hardcoding them in.
Do you see the structure now?
The outer loop prints each layer of the pyramid. The first inner loop prints the white spaces and the second inner loop prints the *
.
来源:https://stackoverflow.com/questions/46680143/logic-behind-printing-pyramid-shape-using-nested-for-loops-in-java