【发布时间】:2012-09-14 10:35:23
【问题描述】:
对于我的 java 类,其中一个练习是使用嵌套的 for 循环打印出菱形。在练习中,您需要使用最少量的输出,同时使用嵌套的 for 循环。另一种规定是每次输出只能输出1个字符,例如单个空格、单个星号或单个结束行语句。
我已经完成了,但我想知道是否有更简单的方法可以做到这一点,或者是否有人有清理我的代码的提示。似乎最终写得比需要的要多。非常感谢任何帮助和提示。 :)
这是最终结果的样子:
这是我的代码:
public class Diamond
{
public static void main(String args[])
{
int b = 11; // secondary asterisk loop counter
int ac = 2; // asterisk count
int sc = 5; // space count
int elc = 2; // end line count
int slc = 1; // space loop count
int sslc = 1; // secondary space loop count
for(int e = 1; e < elc && elc < 12;e++)
{
if(elc <= 6)
{
for(int a = 1; a < ac; a++)
{
for(;sc <= 5 && sc > 0; sc--)
{
System.out.print(" ");
}
System.out.print("*");
}
ac += 2;
sc = 5 - slc;
slc += 1;
}
else if (elc > 6)
{
ac -= 2;
sc = 1;
for (; b < ac ; b++)
{
for(;sc <= sslc && sc > -2; sc++)
{
System.out.print(" ");
}
System.out.print("*");
}
b = 1;
sslc += 1;
}
if(elc != 6)
{
System.out.println();
}
elc += 1;
}
}
}
【问题讨论】: