0

我将如何仅使用for循环生成此序列?

***+++------+++***

我试过这样做,但看起来不正确

String u ="";
for(i=1;i<3;++i)
{
    u = u + "***" + "+++" + "---";
}

System.out.println(u);
4

1 回答 1

5

好吧,你可以这样做:

for (int i = 1; i < 2; ++i) {
    System.out.println("***+++------+++***");
}

但大概这不是你想要的。这个怎么样:

String symbols = "*+-";
for (int s = 0; s < symbols.length(); ++s) {
    char c = s.charAt(s);
    for (int i = 0; i < 3; ++i) {
        System.out.print(c);
    }
}
for (int s = symbols.length() - 1; s >= 0; --s) {
    char c = s.charAt(s);
    for (int i = 0; i < 3; ++i) {
        System.out.print(c);
    }
}
System.out.println();

要不然:

String symbols = "*+-";
int len = symbols.length();
StringBuilder output = new StringBuilder();
for (int s = 0; s < len; ++s) {
    char c = s.charAt(s);
    for (int i = 0; i < 3; ++i) {
        output.append(c);
    }
}
System.out.print(output);
System.out.println(output.reverse());

甚至:

String symbols = "*+-";
int len = symbols.length();
StringBuilder prefix = new StringBuilder();
StringBuilder suffix = new StringBuilder();
for (int s = 0; s < len; ++s) {
    char c1 = s.charAt(s);
    char c2 = s.charAt(len - 1 - 1);
    for (int i = 0; i < 3; ++i) {
        prefix.append(c1);
        suffix.append(c2);
    }
}
System.out.print(prefix);
System.out.println(suffix);
于 2012-11-09T17:18:40.857 回答