首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

for循环题目:求代码打印出下图。该如何处理

2012-04-25 
for循环题目:求代码打印出下图。求用for循环语句打印出如下图所示:11 2 11 2 3 2 11 2 3 4 3 2 1[解决办法]

for循环题目:求代码打印出下图。
求用for循环语句打印出如下图所示:
  1
  1 2 1
  1 2 3 2 1
  1 2 3 4 3 2 1

[解决办法]

Java code
public class Test {    public static void main(String[] args) {        for(int i=1; i<=4; i++) {            int j;            for(j=1; j<=i; j++) {                System.out.print(j + " ");            }            for(j=j-2; j>=1; j--) {                System.out.print(j + " ");            }            System.out.println();        }    }}
[解决办法]
public class shishi {
public static void main(String[] args) {
getNum(1);
}
public static void getNum(int i){
for(int j=1;j<=i;j++){
for(int k=1;k<=(i-j)*2;k++){
System.out.print(" ");
}
for(int h=1;h<=j;h++){
System.out.print(h);
System.out.print(" ");
}
for(int h=j-1;h>=1;h--){
System.out.print(h);
System.out.print(" ");
}
for(int k=1;k<=(i-j)*2;k++){
System.out.print(" ");
}
System.out.println();
}
}


}
//我也是新手,总觉得我写的复杂了点,你看看能不能优化
[解决办法]
Java code
public class Test {    public static void main(String[] args) {         for(int i=1; i<=4; i++) {                int j;                for(j=4;j>i;j--){                    System.out.print("  ");                }                for(j=1; j<=i; j++) {                    System.out.print(j + " ");                }                for(j=j-2; j>=1; j--) {                    System.out.print(j + " ");                }                System.out.println();            }    }} 

热点排行