解释用Java创建金字塔
我正在参加 Java 编程初学者课程,目前正在复习循环。如果有一件事我不明白,那就是金字塔。我在网上研究了书上的练习,找到了金字塔示例的解决方案,但即使看到代码,我仍然不明白,如果我的生活依赖于它,我也无法重新创建答案。
下面是一个金字塔示例以及创建它的代码。如果有人可以浏览代码并给我逐行“傻瓜式”解释正在发生的事情,那么也许我最终会理解。
预先感谢您的帮助!
前任。创建以下金字塔:
<前><代码> 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();
}
}
}
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.
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
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();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
金字塔中有 7 行,因此第一个 for 循环是在行上循环,
第二个 for 循环打印一堆空格,以便三角形不会显示为:
第三个 for 循环(带有 k),有一个条件运算符,其工作原理如下:
因此,它要么将数字 k 添加到字符串中,要么添加一个空格,然后是数字 k 到字符串中。
第四个循环做了类似的事情。
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:
The third for loop (with k), has a conditional operator which works like this:
So it either adds the number k to the string, or adds a space and then the number k to the string.
Fourth loop does a similar thing.
首先将
x
声明为 7。然后for
循环开始。该循环首先将变量i
设为 1。其内容(以{
开头并以相应的}i <= x
) 计算结果为 true,code>) 就会运行。在这样的执行结束时,将执行最后一部分:i++
,它将变量i
增加1。那么会发生什么:
这就是外循环。现在,我们需要弄清楚在 for 循环的一次这样的迭代中会发生什么。让我们看一下执行了 7 次的代码块。
这里有三个逻辑部分,方便地用空行分隔。这里可能令人困惑的是,这三个部分位于外部 for 循环的代码块中,但没有嵌套得更深。看一下第一个:
这次没有
{
或}
来分隔 for 代码块的一部分。默认情况下,这意味着只有下一条语句是其中的一部分,或者在本例中为System.out.print(" ");
。那段代码会发生什么?好吧,这是另一个 for,这次从 1 开始一直运行到
x - i
。x
仍然是 7,但是i
取决于我们所处的外部 for 循环的哪一次迭代。第一轮它将是 1。这将对应于第一个您在输出中看到的行。第二轮将为2
。这将对应于输出的第二行。因此,假设这是外部 for 循环的第一次迭代。
x - i
实际上是7 - 1
,即 6。我们让一些变量j
从 1 到 6。这 6 个中的每一个有时,我们打印出 3 个空格字符。之后,我们到达第二部分:
另一个 for 循环,但有所不同。此示例使用变量
k
,该变量从 i 开始,然后向下计数到 1,如k--
所示。对于每一次迭代,它都会在输出中打印出更多内容。这次打印语句的内容有点复杂。它使用三元运算符。将评估第一位(k >=10)
。如果为 true,则返回:
之前的位,否则返回:
之后的位。在本例中,这意味着如果k
大于或等于 10,它将仅打印k
的值。否则,它将打印出两个空格加上k
的值。在此之后,最后一点应该很容易弄清楚。请注意,在 for 循环及其单个语句之后,有一个
System.out.println();
它所做的只是打印出换行符,使输出转到下一行。这标志着外部 for 循环的一次迭代的结束。只要
i
不大于x
(在我们的例子中是7),另一个迭代就会开始,这三个部分就会运行。由于这三个内部 for 循环依赖于 i,因此它们总是会运行不同的次数。在心里做以下事情:至少迭代三次外层 for 循环。这意味着,想象
i
为 1,并在心里执行{
和}
之间的内容。然后将i
视为 2 并执行相同操作。再重复 3 次,现在应该开始变得清晰了。祝你好运!
It begins by declaring
x
to be 7. Then afor
loop starts. This loop is going to start off by saying a variablei
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 variablei
by one.So what happens is:
That's the outer loop. Now, we'll need to figure out what happens in one such iteration of the for loop. So let's look at that code block which gets executed 7 times.
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:
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 caseSystem.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, buti
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 be2
. That will correspond to the second row of the output.So suppose this is the first iteration of the outer for loop.
x - i
is then really7 - 1
, which is 6. We let some variablej
go from 1 to 6. Each of these 6 times, we're printing out 3 space characters.After that, we arrive at the second part:
Another for loop, but with a twist. This one uses a variable
k
that starts at i and then counts down to 1, as indicated by thek--
. 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 ifk
is larger than or equal to 10, it'll print out justk
's value. Otherwise, it'll print out two spaces plusk
's value.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.That marks the end of one iteration of the outer for loop. As long as
i
is nog larger thanx
(7 in our case), another iteration will start and those three parts are gonna run. Since those three inner for loops are dependent oni
, they're always gonna run a different amount of times.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 ofi
being 2 and do the same. Do it again for 3 and by now it should start to become clear.Good luck!
信用:http://www.skilledmonster.com/ 2013/10/28/java-pyramid-example-pattern-11/
Credit: http://www.skilledmonster.com/2013/10/28/java-pyramid-example-pattern-11/
如果有帮助的话,你也可以尝试一下:)
输出:
代码逻辑:首先将金字塔分成3个三角形。
1> 第一个三角形(空格用#表示)
2> 第二个三角形(用$表示)
3> 第三个三角形(用@表示)
在一起将形成金字塔结构
代码:
You can also try this if it helps :)
OUTPUT:
CODE LOGIC: First divide the pyramid into 3 triangle.
1> First triangle (White spaces represented by #)
2> Second triangle (represented by $)
3> Third triangle (represented by @)
Together it will make a pyramid structure
CODE:
让我们首先了解 For 循环:
For 循环:
它是围绕一组有限的代码重复结构构建的。
因此,如果您想要某个特定的代码块
已经一遍又一遍地运行了特定的次数
For 循环很有帮助。
语法:
eg:
在此“int i=1”是初始化部分,循环会迭代
直到条件成立,即 (I <=x) 替换 I 和 x(1<=7) 的值。
在这条语句之后,循环体内将被执行,最后“i++”,即“I”的值将增加(I 将变为 2)。
每次都会重复这个过程,直到条件 (I <= x) 为真。
现在让我们了解模式是如何形成的:
正如我们所看到的,有两件事需要考虑,首先是行数,其次是列数:
我们使用两个循环来构造这样的结构,首先外部循环用于行数,第二个内部循环用于列数。
代码逻辑:首先将金字塔分成3个三角形。
1> ;第一个三角形(以#表示的空格)
2>第二个三角形(用$表示)
3>第三个三角形(用@表示)
它将形成一个金字塔结构
让我们开始:
现在让我们分解我们的模式问题:
我们将其分成 3 个三角形,每个三角形将在主循环内有自己的循环来获取行数。
正如我们所看到的,我们的模式所需的行数是 7,因此我们将重复第一个循环,直到达到 7 行。
主循环(针对行):
第一个内部循环:
正如我们在形态逻辑中所看到的,第一个三角形将
由空格或空白组成。
“i”的值为“1”,因为这是主循环第一次运行
从那时起“i”的值就没有改变。
when j = 1 : 1 <= 7-1 (will print) ######
//主循环和内循环的第一次迭代。
此控件将进入下一个循环,即第二个内部循环:
j = 2 : 2 <= 7-1 (will print) #####
// 在主循环的第二次迭代中内循环。
此控件将进入下一个循环,即第二个内部循环:
j = 3 : 3 <= 7-1 (will print) ####
// 在主循环和内部循环的第三次迭代中环形。
此控件将进入下一个循环,即第二个内部循环:
j = 4 : 4 <= 7-1 (will print) ###
//在主循环和内部循环的第四次迭代中。
此控件将进入下一个循环,即第二个内部循环:
j = 5 : 5 <= 7-1(将打印)##
// 主循环和内循环的第五次迭代。
此控件将进入下一个循环,即第二个内部循环:
j = 6 : 6 <= 7-1 (will print) #
//在主循环和内部循环的第六次迭代上。
此控制将进入下一个循环,即第二个内部循环:
j = 7 : 7 <= 7-1 //第一个内部循环结束(7<=6 不为 true)
第二个内部循环 :< /strong>
注意:
// 如果测试条件为 true,则结果将得到 value1,否则 value 2
第一次迭代:K=i(我们知道 i=1),因此 k=1; k>=1(替换变量我们得到 1>=1 这是真的);执行语句。
语句: System.out.print((k >= 10) ?+ k : " " + k);
或者
如果(1>=10)?然后打印“k”的值(即1),
否则打印“k”的vlaue,k前面有一些空格
(为了使金字塔看起来间隔均匀)
注意:如果你对三元运算符感到困惑,那么不要使用它,你可以简单地写。
第三个内部循环: 该循环用于打印第三个三角形。
让我们看看完整的代码:
Let's First understand For loop:
For Loop:
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.
Syntax:
eg:
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).
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).
This process will repeat every time till the condition (I <= x) is true.
Now lets understand how pattern are form:
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.
1> First triangle (White spaces represented by #)
2> Second triangle (represented by $)
3> Third triangle (represented by @)
Together it will make a pyramid structure
Lets begin :
Now lets breakdown our pattern problem:
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.
main loop (for rows):
First inner loop:
As we have seen in pattern logic that the first triangle will
consist of white spaces or blank.
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.
when j = 1 : 1 <= 7-1 (will print) ######
//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) #####
// 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) ####
// 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) ###
//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.
after this control will go to the next loop i.e second inner loop:
j = 6 : 6 <= 7-1 (will print) #
//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)
Second inner loop :
NOTE:
// if testcondition is true then result will get value1 else value 2
First iteration: K=i (we know i=1) so k=1; k>=1 (Replacing variables we get 1>=1 which is true); execute statements.
Statement:
System.out.print((k >= 10) ?+ k : " " + k);
or
if(1>=10)? then print value of "k" (that is 1)
else print vlaue of "k" with some spaces ahead k
(in order to make the pyramid look even spaced)
NOTE: if you are getting confused with ternary operator then don't use it, you can simply wirte.
Third inner loop: This loop is used to print the third triangle.
lets see full code:
我们也可以用一个 for 循环来制作金字塔,使其在执行时间方面表现出高效的代码。
这是打印星号金字塔的代码。
输出:
We can make pyramid with one for loop as well, making it performance efficient code in terms of execution time.
Here is the code which prints pyramid of asterisk.
output:
好吧,我做了一个类似的程序,没有任何问题,只是想象力......代码是如此清晰:D
well I made a similar program with no issues and just imagination... the code is so clear :D