【发布时间】:2018-12-19 17:32:07
【问题描述】:
我不知道如何使用嵌套循环向上计数然后向下计数。目前,我的输出是:
2
33
444
5555
66666
当我希望它像这样输出时:
2
33
444
33
2
我不确定如何解决这个问题。我一直在研究这个问题,但似乎不知道如何改变它来使其工作。
这是我当前产生第一个输出的代码:
【问题讨论】:
标签: java loops nested-loops
我不知道如何使用嵌套循环向上计数然后向下计数。目前,我的输出是:
2
33
444
5555
66666
当我希望它像这样输出时:
2
33
444
33
2
我不确定如何解决这个问题。我一直在研究这个问题,但似乎不知道如何改变它来使其工作。
这是我当前产生第一个输出的代码:
【问题讨论】:
标签: java loops nested-loops
这个输出有两个有趣的属性。对于每一行i,我们可以这样说:
i 和times - i 之间的最小值。如果你把所有这些放在一起:
int lines = 3;
int times = lines * 2;
String output = "";
for(int i = 1; i < times; i++)
{
int numChar = Math.min(i, times - i);
int toPrint = numChar + 1;
for(int k = 1; k < toPrint; k++) {
output += toPrint;
}
output += "\n";
}
System.out.println(output);
【讨论】:
在您的示例中,您的第二个内部循环什么都不做,它永远不会启动,只有第一个产生输出。我认为你的想法接近有四个循环,两个两个嵌套。这可行,但您只需要巧妙地使用两个嵌套循环。
public static void main(String[] args){
int lines = 3;
int times = lines * 2;
int x = 2;
String output = "";
for(int i = 1; i < times; i++) {
for (int k = 1; k <= Math.min(times-i, i); k++) {
output = output + x;
}
//Update the index
if (i < times/2) {
x++;
} else {
x--;
}
output += "\n";
}
System.out.println(output);
}
诀窍在于如何使用第二个循环的索引:Math.min(times-i, i)。
编辑: 编辑后,您似乎希望数字“旋转”(即 ...8,9,0,1...)。为了实现这一点,您可以在内部循环中执行:
String xS = String.valueOf(x);
output += xS.charAt(xS.length()-1);
另一个选项(在内循环之外):
//Update the index
if (i <= (times/2) - 1) {
x++;
} else {
x--;
}
x = x%10; //the rest of dividing x by 10
output += "\n";
}
【讨论】: