这是代码,问题是在第二个嵌套循环中,它涉及数字,第二个嵌套循环每重复一次,就会减少-3
`// b is the repetition and cn is the starting point which it means it falsify this 14 <= 5 which is wrong
String name = "Hotdogs" int b = 5, cn = 14 char k = name.charAt(0);
//start of the 1st loop
for (int i = 1; i <= b; i++) {
for (int p = i; p <= b; p++) {
System.out.print(k+ " ");
}
System.out.println();
//end of the 1st loop
//start of the 2nd loop
for (int a = cn; a <= b; a= a-3) {
for (int z = cn; z <= a; z++) {
System.out.print(cn+ " ");
}
System.out.println();
//end of the 2nd loop`因此,我期待第二个嵌套循环是做一个半金字塔模式,即:字母的一个是第一个嵌套的循环,有数字的一个是第二个嵌套的循环,这里是预期的输出。

发布于 2022-04-05 02:13:43
我们可以很容易地通过修改循环的工作方式来解决这个问题。这看起来像一个家庭作业问题,所以我不只是复制下面的代码,我鼓励您阅读官方教程来了解它是如何工作的,甚至在下面的代码中使用循环变量来查看您修改它们时的变化。
快速解释for循环是如何工作的。因此,如果我们编写了这样的for循环:
for (int i = 0; i < 5; i++) {...这就是引擎盖下正在发生的事情:
for (initialization; termination; increment) {...第一部分int i = 0是循环从何处开始的初始化。
第二部分i < 5是终止条件,它导致循环在我不再小于5时停止。
最后一部分i++是增量,或每次循环结束时更改的内容。
注意,对于最后一个增量条件,我们可以做各种各样的事情,它不一定是i++,我们可以用i--减少它,甚至做一些数学i = i*2。
所以当涉及到你的问题。在第一个循环中,简单的解决方案是向后工作,方法是使用b值作为初始化值,比如so for (int i = b;,我们希望向后工作,所以我们使用i--作为增量操作,最后我们使用中间的i > 0;作为终止,这样我们就可以停止其中的一个,我们点击0:
//start of the 1st loop
for (int i = b; i > 0; i--) {
//...
}现在,对于内环,我们只需要稍微修改它,以便它运行正确的次数,并在内环后面添加System.out.println();,这样行就正确了:
//start of the 1st loop
for (int i = b; i > 0; i--) {
for (int p = 0; p < i; p++) {
System.out.print(k+ " ");
}
//Move to the next line
System.out.println();
}对于第二个循环,我们只需从0开始,并按正常方式工作:
//start of the 2nd loop
for (int i = 0; i < b; i++) {
//...
}有趣的部分是内部循环,它也是从0开始正常工作的,我们只使用一些逻辑,一个简单的简短计算int value = cn - (p*3);来计算打印值需要是什么。这是因为p的值改变了每个循环,并将从cn中减去3的倍数,从而得到14 11 8 5.诸如此类:
//start of the 2nd loop
for (int i = 0; i < b; i++) {
for (int p = 0; p <= i; p++) {
//calculate value using cn - i*3 (To get -3 for each number)
int value = cn - (p*3);
System.out.print(value+ " ");
}
//Move to the next line
System.out.println();
}
//end of the 2nd loop`产出如下:
H H H H H
H H H H
H H H
H H
H
14
14 11
14 11 8
14 11 8 5
14 11 8 5 2 发布于 2022-04-05 02:43:38
假设两组不同的嵌套for循环,下面是两种方法的替代方法:
String name = "Hotdogs";
int b = 5, cn = 14;
char k = name.charAt(0);
for (int row=1; row<=b; row++) {
for (int col=row; col<=b; col++) {
System.out.print(k + " ");
}
System.out.println();
}
for (int row=1; row<=b; row++) {
for (int col=1, x=cn; col<=row; col++, x=x-3) {
System.out.print(x + " ");
}
System.out.println();
}注意,在生成数字的第二组嵌套for循环中,在内部for循环中,我们声明了两个不同的变量,并且有两个用逗号分隔的不同的增量。
产生的产出:
H H H H H
H H H H
H H H
H H
H
14
14 11
14 11 8
14 11 8 5
14 11 8 5 2https://stackoverflow.com/questions/71744932
复制相似问题