import static java.lang.System.*;
import java.util.Scanner;
public class TriangleFour{
public static void createTriangle(int size, String let){
String output = "";
String x = let;
int y = size;
for (int z = size; z > 0; z--){
int p = z;
output += "\n";
while (p > 0){
output = output + " ";
p--;
}
for (int d = size; d >= y; d--){
output = output + x;
}
y--;
}//End of for loop
out.println(output);
}
}
当在我的程序中执行此语句 TriangleFour.createTriangle(3, "R");
时,此代码会产生以下输出:
R
RR
RRR
我想修改我的代码以基本上翻转输出,如下所示:
RRR
RR
R
如有任何帮助,我们将不胜感激。
最佳答案
这是我的尝试。我精简了你的代码,并重命名了一些变量以使其更清晰。
public static void createTriangle(int size, String let){
for(int i=size;i>0;i--){
int fill = i;
int space = size-i;
while(space>0){
System.out.print(" ");
space--;
}
while(fill>0){
System.out.print(let);
fill--;
}
System.out.println();
}
}
几乎第一个 for 循环决定了会有多少行。如果 size
为 3,则将有 3 行。第一个 while 循环控制每行的空白空间量。 space
是要打印的空格数,fill
是要打印的字母数。每次循环运行时,您都需要 space
+ fill
= size
。
因此,在第一个循环中,space
为 0。您不会打印任何空格。 fill
为 3,因此打印 3 个字母,0 + 3 = 3。
RRR
第二次循环,空格
为1,打印1个空格。 填充
为2,打印2个字母,1 + 2 = 3。
RRR
RR
第三次循环,空格
为2,打印2个空格。 fill
为1,打印1个字母。 2+1=3
RRR
RR
R
希望这是有道理的。
关于java - 更改与 Java 中的嵌套循环相关的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33559034/