解释在 Java 中创建金字塔
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7905617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Explain creating a pyramid in Java
提问by user1011064
I am in a beginner java programming class and currently reviewing loops. If there is one thing I just do not understand, it's pyramids. I have researched the book exercises online and found the solutions to the pyramid examples, but even seeing the code, I still don't understand and couldn't recreate the answers if my life depended on it.
我在初级 Java 编程课程中,目前正在复习循环。如果有一件事我不明白,那就是金字塔。网上查了书上的习题,找到了金字塔例子的解法,但即使是看到代码,还是看不懂,也无法复现答案。
Below is a pyramid example and the code that creates it. If someone could walk through the code and give me a line by line 'for dummies' explanation of what is going on then maybe I'll finally understand.
下面是一个金字塔示例和创建它的代码。如果有人可以遍历代码并给我一行一行的“傻瓜”解释,那么也许我最终会明白。
Thanks in advance for you help!
在此先感谢您的帮助!
ex. create the following pyramid:
前任。创建以下金字塔:
1 2 1 2 3 2 1 2 3 4 3 2 1 2 3 4 5 4 3 2 1 2 3 4 5 6 5 4 3 2 1 2 3 4 5 6 7 6 5 4 3 2 1 2 3 4 5 6 7
1 2 1 2 3 2 1 2 3 4 3 2 1 2 3 4 5 4 3 2 1 2 3 4 5 6 5 4 3 2 1 2 3 4 5 6 7 6 5 4 3 2 1 2 3 4 5 6 7
class Pyramid {
public static void main(String[] args) {
int x = 7;
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= x - i; j++)
System.out.print(" ");
for (int k = i; k >= 1; k--)
System.out.print((k >= 10) ?+ k : " " + k);
for (int k = 2; k <=i; k++)
System.out.print((k >= 10) ?+ k : " " + k);
System.out.println();
}
}
}
回答by NickLH
There are 7 rows in the pyramid, so the first for loop is looping over the rows, the second for loop is printing a bunch of spaces so that the triangle doesnt appear as:
金字塔中有 7 行,所以第一个 for 循环在行上循环,第二个 for 循环打印一堆空格,这样三角形就不会显示为:
1
2 1 2
3 2 1 2 3
The third for loop (with k), has a conditional operator which works like this:
第三个 for 循环(带 k)有一个条件运算符,其工作方式如下:
boolean-expression ? result-if-true : result-if-false
So it either adds the number k to the string, or adds a space and then the number k to the string.
因此,它要么将数字 k 添加到字符串中,要么添加一个空格,然后将数字 k 添加到字符串中。
Fourth loop does a similar thing.
第四个循环做类似的事情。
回答by G_H
It begins by declaring x
to be 7. Then a for
loop starts. This loop is going to start off by saying a variable i
to be 1. Its contents (the code block starting with {
and ending with the corresponding }
) will be run as long as the for loop's second part (i <= x
) evaluates to true. At the end of such an execution, the last part is going to be performed: i++
, which increments variable i
by one.
它首先声明x
为 7。然后for
循环开始。这个循环将以变量i
为 1 开始。只要 for 循环的第二部分 ( ) 的计算结果为真,它的内容({
以相应的开头和结尾的代码块}
)就会运行i <= x
。在这样的执行结束时,将执行最后一部分:i++
,将变量i
加一。
So what happens is:
那么会发生什么:
- i set to 1
- i <= x ?
- Yes! 1 is smaller than or equal to 7. Do the stuff in the code block.
- i goes from 1 to 2
- i <= x ?
- Yes! 2 is smaller than or equal to 7. Do the stuff in the code block.
- ... several iterations ...
- i goes from 7 to 8
- i <= x ?
- No! 8 is not smaller than or equal to 7. For loop ends.
- 我设置为 1
- 我 <= x ?
- 是的!1 小于或等于 7。做代码块中的东西。
- 我从 1 到 2
- 我 <= x ?
- 是的!2 小于或等于 7。做代码块中的东西。
- ... 多次迭代 ...
- 我从 7 到 8
- 我 <= x ?
- 不!8 不小于等于 7。for 循环结束。
That's the outer loop. Now, we'll need to figure out what happens in onesuch iteration of the for loop. So let's look at that code block which gets executed 7 times.
这就是外循环。现在,我们需要弄清楚在 for 循环的一次这样的迭代中会发生什么。因此,让我们看一下执行 7 次的代码块。
for (int j = 1; j <= x - i; j++)
System.out.print(" ");
for (int k = i; k >= 1; k--)
System.out.print((k >=10) ?+ k : " " + k);
for (int k = 2; k <=i; k++)
System.out.print((k>= 10) ?+ k : " " + k);
System.out.println();
There's three logical parts here, conveniently separated by a blank line. What may be confusing here is that these three parts are in the outer for loop's code block, but are not nested any deeper. Take a look at this first one:
这里有三个逻辑部分,方便地由一个空行分隔。这里可能令人困惑的是,这三个部分位于外部 for 循环的代码块中,但没有嵌套更深。看看第一个:
for (int j = 1; j <= x - i; j++)
System.out.print(" ");
This time there's no {
or }
to delimit what is part of the for's code block. By default, this means only the next statement is part of it, or in this case System.out.print(" ");
.
这一次没有{
or}
来界定 for 代码块的一部分。默认情况下,这意味着只有下一个语句是它的一部分,或者在这种情况下System.out.print(" ");
。
What happens in that bit of code? Well, it's another for, this time starting from 1 and running until x - i
. x
is still 7, but i
depends on which iteration of the outer for loop we're in. First time round it'll be 1. That will correspond to the first row you see in the output. Second time round it'll be 2
. That will correspond to the second row of the output.
这段代码会发生什么?嗯,这是另一个 for,这次从 1 开始运行到x - i
. x
仍然是 7,但i
取决于我们所处的外部 for 循环的哪个迭代。第一次它会是 1。这将对应于您在输出中看到的第一行。第二轮它将是2
。这将对应于输出的第二行。
So suppose this is the first iteration of the outer for loop. x - i
is then really 7 - 1
, which is 6. We let some variable j
go from 1 to 6. Each of these 6 times, we're printing out 3 space characters.
所以假设这是外部 for 循环的第一次迭代。x - i
然后真的7 - 1
是 6。我们让一些变量j
从 1 到 6。这 6 次中的每一次,我们都打印出 3 个空格字符。
After that, we arrive at the second part:
之后,我们来到第二部分:
for (int k = i; k >= 1; k--)
System.out.print((k >=10) ?+ k : " " + k);
Another for loop, but with a twist. This one uses a variable k
that starts at i and then counts downto 1, as indicated by the k--
. For each of these iterations, it prints out more stuff to the output. The content of the print statement is a bit more complex this time. It uses a ternary operator. That first bit (k >=10)
is going to be evaluated. If it is true, it'll return the bit before :
, otherwise it'll return the bit after :
. In this case, it means that if k
is larger than or equal to 10, it'll print out just k
's value. Otherwise, it'll print out two spaces plus k
's value.
另一个 for 循环,但稍有不同。这个变量使用k
从 i 开始然后倒数到 1的变量,如k--
. 对于这些迭代中的每一次,它都会将更多内容打印到输出中。这次打印语句的内容有点复杂。它使用三元运算符。(k >=10)
将评估第一位。如果为真,则返回之前的位:
,否则返回之后的位:
。在这种情况下,这意味着如果k
大于或等于 10,它将打印出 justk
的值。否则,它会打印出两个空格 plusk
的值。
After this, the last bit should be easy to figure out. Notice that after the for loop and its single statement, there's a System.out.println();
All this does is print out a line break, making the output go to the next line.
在此之后,最后一点应该很容易弄清楚。请注意,在 for 循环及其单个语句之后,有一个System.out.println();
All this 是打印一个换行符,使输出转到下一行。
That marks the end of one iteration of the outer for loop. As long as i
is nog larger than x
(7 in our case), another iteration will start and those three parts are gonna run. Since those three inner for loops are dependent on i
, they're always gonna run a different amount of times.
这标志着外部 for 循环的一次迭代结束。只要i
nog 大于x
(在我们的例子中为 7),另一个迭代将开始并且这三个部分将运行。由于这三个内部 for 循环依赖于i
,它们总是会运行不同的次数。
Mentally do the following: go through at least three iterations of the outer for loop. That means, think of i
being 1 and mentally execute the stuf between {
and }
. Then think of i
being 2 and do the same. Do it again for 3 and by now it should start to become clear.
精神上执行以下操作:至少进行 3 次外部 for 循环迭代。这意味着,想i
为1和精神上执行之间塞入{
和}
。然后想想i
是2并做同样的事情。再做 3 次,现在它应该开始变得清晰了。
Good luck!
祝你好运!
回答by Abhi
You can also try this if it helps :)
如果有帮助,你也可以试试这个:)
*
***
*****
*******
*********
OUTPUT:
输出:
ROW (1) * --> COLUMN
| (2) *
| (3) ***
| (4) *****
v (5) *******
CODE LOGIC: First divide the pyramid into 3 triangle.
代码逻辑:首先将金字塔分成3个三角形。
####$
###$$@
##$$$@@
#$$$$@@@
$$$$$@@@@
1> First triangle(White spaces represented by #)
1>第一个三角形(用#表示的空格)
####
###
##
#
2> Second triangle(represented by $)
2>第二个三角形(用$表示)
$
$$
$$$
$$$$
$$$$$
3> Third triangle(represented by @)
3>第三个三角形(用@表示)
#
@
@@
@@@
@@@@
Together it will make a pyramid structure
它将一起构成一个金字塔结构
CODE:
代码:
pyramid() {
for (int i = 1; i <= 5; i++) { // loop row
for (int k = 1; k <= 5 - i; k++) { // 1st triangle (printing space)
System.out.print(" ");
}
for (int j = 1; j <= i; j++) { // 2nd triangle
System.out.print("*");
}
for (int l = 1; l <= i - 1; l++) { //3rd triangle
if (i == 1) {
break;
}
System.out.print("*");
}
System.out.println();
}
}
回答by Abhi
Let's First understand For loop:
先来了解一下For循环:
For Loop:
For循环:
It is structured around a finite set of repetitions of code. So if you have a particular block of code that you want to have run over and over again a specific number of times the For Loop is helpful.
它是围绕一组有限的重复代码构建的。因此,如果您有一个特定的代码块,您希望它一遍又一遍地运行特定次数,那么 For 循环会很有帮助。
Syntax:
句法:
for(initilization; conditional expression; increment expression)
{
//repetition code here
}
eg:
例如:
int x = 7;
for (int i = 1; i <= x; i++){
// statements
}
In this "int i=1" is an initialization part, the loop will iterate till condition is true that is (I <=x) replace the value of I and x(1<=7).
在这个“int i=1”是一个初始化部分,循环将迭代直到条件为真,即(I <=x)替换I和x(1<=7)的值。
After this statement inside the loop body will be executed and in the end "i++" that is the value of "I" will be incremented (I will become 2).
在循环体内的这条语句将被执行之后,最后“i++”即“I”的值将增加(I 将变为 2)。
This process will repeat every time till the condition (I <= x) is true.
这个过程每次都会重复,直到条件 (I <= x) 为真。
Now lets understand how pattern are form:
现在让我们了解模式是如何形成的:
ROW (1) * --> COLUMN
| (2) **
| (3) ***
| (4) *****
v (5) *******
As we can see there are two things that need to be considered first the number of rows and second the number of columns:
正如我们所看到的,需要考虑两件事,首先是行数,其次是列数:
We use two loops to construct such structures, first outer loop for number of rows and second inner loop for number of columns.
我们使用两个循环来构建这样的结构,第一个外部循环用于行数,第二个内部循环用于列数。
CODE LOGIC: First divide the pyramid into 3 triangle.
代码逻辑:首先将金字塔分成 3 个三角形。
####$
###$$@
##$$$@@
#$$$$@@@
$$$$$@@@@
1> First triangle (White spaces represented by #)
1>第一个三角形(用#表示的空格)
####
###
##
#
2> Second triangle (represented by $)
2>第二个三角形(用$表示)
$
$$
$$$
$$$$
$$$$$
3> Third triangle (represented by @)
3> 第三个三角形(用@表示)
# @ @@ @@@ @@@@
# @ @@ @@@ @@@@
Together it will make a pyramid structure
它将一起构成一个金字塔结构
Lets begin:
让我们开始:
Now lets breakdown our pattern problem:
现在让我们分解我们的模式问题:
######1
#####212
####32123
###4321234
##543212345
#65432123456
7654321234567
We will break this into 3 triangles and every triangle will have its own loop inside the main loop for the number of rows. As we can see a number of rows required for our pattern are 7 so we will make the first loop to repeat till 7 rows are achieved.
我们将把它分成 3 个三角形,每个三角形在主循环内都有自己的循环,用于行数。正如我们所看到的,我们的模式所需的行数是 7,因此我们将重复第一个循环,直到达到 7 行。
main loop (for rows):
主循环(用于行):
int x = 7;
for (int i = 1; i <= x; i++) { // main loop for number of rows
// other 3 loops will come insidethe mail loop
}
First inner loop:As we have seen in pattern logic that the first triangle will consist of white spaces or blank.
第一个内循环:正如我们在模式逻辑中看到的,第一个三角形将由空格或空白组成。
output eg: (representing white spaces with #)
######
#####
####
###
##
#
for (int j = 1; j <= x - i; j++) // j represent a column number
System.out.print(" ");
// This will create blank spaces till the condition is true.
**condition explained:** j <= x - i
Value of "i" is "1" as this is the first time the main loop is running and ever since the value of "i" has not changed.
“i”的值为“1”,因为这是主循环第一次运行,并且“i”的值没有改变。
**replace values:**
when j = 1 : 1 <= 7-1 (will print) ######
当 j = 1 : 1 <= 7-1 (将打印)######
//first iteration of main loop and inner loop.
//主循环和内循环的第一次迭代。
after this control will go to the next loop i.e second inner loop:
在此控制将进入下一个循环后,即第二个内循环:
j = 2 : 2 <= 7-1 (will print) #####
j = 2 : 2 <= 7-1(将打印)#####
// on second iteration of main loop and inner loop.
// 在主循环和内循环的第二次迭代中。
after this control will go to the next loop i.e second inner loop:
在此控制将进入下一个循环后,即第二个内循环:
j = 3 : 3 <= 7-1 (will print) ####
j = 3 : 3 <= 7-1(将打印)####
// on third iteration of main loop and inner loop.
// 在主循环和内循环的第三次迭代中。
after this control will go to the next loop i.e second inner loop:
在此控制将进入下一个循环后,即第二个内循环:
j = 4 : 4 <= 7-1 (will print) ###
j = 4 : 4 <= 7-1(将打印)###
//on fourth iteration of main loop and inner loop.
//在主循环和内循环的第四次迭代中。
after this control will go to the next loop i.e second inner loop:
在此控制将进入下一个循环后,即第二个内循环:
j = 5 : 5 <= 7-1 (will print) ##
// on fifth iteration of main loop and inner loop.
j = 5 : 5 <= 7-1(将打印)##
// 在主循环和内循环的第五次迭代中。
after this control will go to the next loop i.e second inner loop:
在此控制将进入下一个循环后,即第二个内循环:
j = 6 : 6 <= 7-1 (will print) #
j = 6 : 6 <= 7-1(将打印)#
//on sixth iteration of main loop and inner loop.
//在主循环和内循环的第六次迭代中。
after this control will go to the next loop i.e second inner loop:
在此控制将进入下一个循环后,即第二个内循环:
j = 7 : 7 <= 7-1 //end of first inner loop as (7<=6 is not true)
j = 7 : 7 <= 7-1 // 第一个内循环结束 as (7<=6 is not true)
Second inner loop :
第二个内循环:
for (int k = i; k >= 1; k--) //second triangle
System.out.print((k >= 10) ?+ k : " " + k); // ternary operator is used to check the printing logic
NOTE:
笔记:
ternary operator syntax: result = testCondition ? value1 : value2
// if testcondition is true then result will get value1 else value 2
// 如果 testcondition 为真,则结果将获得 value1 否则 value 2
***DIY: (Take a paper pen)***
Implement for loop logic and replace variables with values:
First iteration: K=i (we know i=1) so k=1; k>=1 (Replacing variables we get 1>=1 which is true); execute statements.
第一次迭代:K=i(我们知道i=1)所以k=1;k>=1(替换变量我们得到 1>=1,这是真的);执行语句。
Statement: System.out.print((k >= 10) ?+ k : " " + k);
or
if(1>=10)? then print value of "k" (that is 1)
语句: System.out.print((k >= 10) ?+ k : " " + k);
还是 if(1>=10)?然后打印“k”的值(即1)
else print vlaue of "k" with some spaces ahead k (in order to make the pyramid look even spaced)
else 打印“k”的值,k 前面有一些空格(为了使金字塔看起来间隔均匀)
NOTE:if you are getting confused with ternary operator then don't use it, you can simply wirte.
注意:如果您对三元运算符感到困惑,请不要使用它,您可以简单地编写。
System.out.print(" " + k); // will give same output
after this control will go to the next loop i.e third inner loop:
在此控制将进入下一个循环后,即第三个内循环:
*Second innerloop is used to print this portion:*
1
21
321
4321
54321
654321
7654321
Third inner loop:This loop is used to print the third triangle.
第三个内循环:这个循环用于打印第三个三角形。
2
23
234
2345
23456
234567
for (int k = 2; k <=i; k++) // loop column
System.out.print((k >= 10) ?+ k : " " + k);
or
System.out.print(" " + k)
lets see full code:
让我们看看完整的代码:
int x = 7;
for (int i = 1; i <= x; i++) { // loop row
for (int j = 1; j <= x - i; j++) // loop column (Triangle one)
System.out.print(" ");
for (int k = i; k >= 1; k--) // loop column (Triangle two)
System.out.print( " " + k);
for (int k = 2; k <=i; k++) // loop column (Triangle three)
System.out.print( " " + k);
System.out.println(); // used to go on new line (new row)
}
回答by Aftaab Siddiki
We can make pyramid with one for loop as well, making it performance efficient code in terms of execution time.
我们也可以用一个 for 循环制作金字塔,使其在执行时间方面具有高效的代码性能。
Here is the code which prints pyramid of asterisk.
这是打印星号金字塔的代码。
public class PyramidPrinting {
public static void main(String[] args) {
int h = 5;
int i,j;
char[] arr = new char[2*h-1];
for(i=h-1,j=h-1; i>=0 && j<=2*h-1; i--,j++){
arr[i]='*';
arr[j]='*';
System.out.println(arr);
}
}
}
output:
输出:
*
***
*****
*******
*********
回答by Ruk Dee Wa
public static void main(String[] args) {
// levels in the pyramid
int x = 5;
for (int i = 1; i <= x; i++) {
// for spacing
for (int j = 1; j <= x - i; j++){ System.out.print(" "); } // left half of the pyramid for (int k = i; k >= 1; k--){
System.out.print((k >= 10) ? +k : " " + k);
}
// corresponding right half of the pyramid
for (int k = 2; k <= i; k++) { System.out.print((k >= 10) ? +k : " " + k);
}
// next line
System.out.println();
}
}
Credit: http://www.skilledmonster.com/2013/10/28/java-pyramid-example-pattern-11/
信用:http: //www.skilledmonster.com/2013/10/28/java-pyramid-example-pattern-11/
回答by Prakhar Londhe
well I made a similar program with no issues and just imagination... the code is so clear :D
好吧,我做了一个类似的程序,没有问题,只是想像……代码很清楚:D
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int i,j,k, n = Integer.parseInt(jTextField1.getText());
for(i=1;i<=n;i++) // normal loop
{
for(j=1; j<=(n-i);j++)
{
System.out.print(" "); // loop for spaces
}
for(k=1;k<=i;k++) // loop for printing numbers
{
System.out.print(k+" ");
}
System.out.println();
} // TODO add your handling code here:
}