我正在尝试推出以下模式的字符:
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
,而且我知道我必须使用空格并插入它们。然而,我被这个非常简单的任务困住了。
编辑:任务是只使用两个循环。不过,我想出了一种使用3的方法,但我无法直接找到一种使用两个循环的方法。
发布于 2017-04-27 21:56:48
由于这个问题有许多不同的可能答案,这只是一个可能的解决办法。
对于这个解决方案,我不需要在X之后打印空格,我只打印前面的空格。
int baseWidth = 10;
for (int a = baseWidth ; a > 0 ; a--) {
for (int b = 0 ; b < a - 1 ; b++) {
System.out.print(" ");
}
for (int b = a - 1 ; b < baseWidth - (a - 1) ; b++) {
System.out.print("X");
}
System.out.print("\n");
}
对于baseWidth =10,上述代码的结果如下:
XX
XXXX
XXXXXX
XXXXXXXX
XXXXXXXXXX
对于baseWidth =9,上述代码的结果如下:
X
XXX
XXXXX
XXXXXXX
XXXXXXXXX
在编辑文章之后,下一个代码片段执行与前一个相同的功能,但只有两个循环。
int baseWidth = 9;
for (int a = baseWidth ; a > 0 ; a--) {
for (int b = 0 ; b < baseWidth - (a - 1) ; b++) {
if (b < a - 1) {
System.out.print(" ");
}
if (b >= a - 1 && b < baseWidth - (a - 1)) {
System.out.print("X");
}
}
System.out.print("\n");
}
发布于 2017-04-27 22:43:06
我没有使用两个for
循环,而是使用了一个for
循环和一个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
发布于 2017-04-27 21:45:10
只要使用一个循环,就可以解决问题,可以将padLeft
与String.format
结合使用,下面是一个简单的示例:
public static void main(String args[]) {
int n = 5;
String str;
for (int i = n; i > 0; i--) {
str = String.format("%0" + ((n - i) * 2 + 1) + "d", 0).replace("0", "x");
System.out.println(String.format("%1$" + ((i - 1 + str.length())) + "s", str));
}
}
输出
x
xxx
xxxxx
xxxxxxx
xxxxxxxxx
https://stackoverflow.com/questions/43668323
复制相似问题