JAVA小程序是关于FOR循环的

来源:百度知道 编辑:UC知道 时间:2024/06/05 03:20:14
要求输出图形:

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

我编写的小程序如下:
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(' ');
}
}