热气球 飞艇 载人:JAVA小程序是关于FOR循环的

来源:百度文库 编辑:神马品牌网 时间:2024/05/07 12:02:31
要求输出图形:

* *
* *
* *
* *
* *
* *
* *

我编写的小程序如下:
public class Lianxi4{
public static void main(String[] args){
int i,j,k;
for (i=0;i<=4;i++){
for (j=0;j<=3-i;j++)
System.out.print(" ");
System.out.print("*");
for (k=1;k<=2*i-1;k++)
System.out.print(" ");
System.out.print("*");
System.out.println();
}
for (i=0;i<=3;i++){
for (j=0;j<=i;j++)
System.out.print(" ");
System.out.print("*");
for (k=0;k<=4-2*i;k++)
System.out.print(" ");
System.out.print("*");
System.out.println();
}
}
}

可是输出的结果却有点差别,
**
* *
* *
* *
* *
* *
* *
* *
**
请高手帮忙,我感觉真的只是一个小问题,可是我已经想破脑袋了,大家帮帮忙啊。

for循环内的结构有问题
for (j=0;j<=3-i;j++)
System.out.print(\" \");
System.out.print(\"*\");
for (k=1;k<=2*i-1;k++)
System.out.print(\" \");
System.out.print(\"*\");
System.out.println();
第一次执行的时候,在这段的第3行和第6行就输出了两个*,建议你先在每个for循环后面加上{},方便你看到这个循环控制的范围。

顺便自己也写了一种方法。
public class LingXing{
private static boolean check(int x, int y, int z){
x = Math.abs(x - z);
y = Math.abs(y - z);
if(x * x + y * y == (z - x) * (z - x) + (z - y) * (z - y)){
return true;
}
return false;
}
public static void main(String[] args){
int count = 4; //菱形边上的星数
for(int i = 0; i < count*2 + 1; i++ ){
for(int j = 0; j < count*2 + 1; j++){
if(check(i, j, count)){
System.out.print("*");
}
else{
System.out.print(' ');
}
}
System.out.println("");
}
}
}

我猜你是想要一个菱形

public class Test{
public void star(int i){
for(int j=1; j<=i; System.out.print('*'),j++);
}

public void space(int i){
for(int j=1; j<=i; System.out.print(' '),j++);
}

public static void main(String[] args){
Test t = new Test();
int i,j,k;
t.space(8); t.star(1); System.out.println("");
for (i=2;i<=5;i++){
t.space(10-2*i);
t.star(1);
t.space(2+(i-2)*4);
t.star(1);
System.out.println("");
}

for(i=1; i<=3; i++){
t.space(2*i);
t.star(1);
t.space(10-(i-1)*4);
t.star(1);
System.out.println("");
}
t.space(8); t.star(1); System.out.println("");
}
}

我也没什么好方法,重复代码较多,第一行和最后一行独立打印