我正在尝试输出以下字符模式:
x
xxx
xxxxx
xxxxxxx
xxxxxxxxx
这就是我目前拥有的:
String y = "";
for(int i = 0; i < 10; i++)
{
y="";
for(int s = 0; s < i; s++)
{
y+= "x";
}
System.out.println(y);
}
此输出
x
xx
xxx
xxxx
xxxxx
xxxxxx
xxxxxxx
xxxxxxxx
这是一种方法。我很清楚每次执行循环时目标模式都会增加两个 x
,并且我知道我必须使用空格并插入它们。然而,我却被这个非常简单的任务困住了。
编辑:任务是仅使用两个循环。不过,我想到了一种使用三个循环的方法,但无法直接找出使用两个循环的方法。
最佳答案
我没有使用两个 for
循环,而是使用了 1 个 for
循环和 1 个 if
语句(这不是循环)。
String spaces = " ";
String word = "";
String X = "x";
for(int i = 10; i > 0; i--) {
if (i%2 == 0) {
word = spaces + X;
System.out.println(word);
spaces = spaces.replaceFirst(" ","");
X += "xx";
}
}
输出就是您所要求的:
x
xxx
xxxxx
xxxxxxx
xxxxxxxxx
关于java - 以编程方式将文本输出置于 for 循环中居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43668323/