如何在JAVA中循环编写数字

时间:2016-05-01 08:54:01

标签: java while-loop

---------1        
--------123   
-------54321  
------1234567  
-----987654321

10行

有人可以建议如何在Java中循环编写代码吗?

2 个答案:

答案 0 :(得分:1)

你在这里: -

public class CreateShapeUsingWhile {
    public static void main(String[] args) {
        int i=10;
        int j=1;
        int k=1;
        int count=2;
        int counter=0;

        while(i>0){
            System.out.println();
            j=1;
            while(j<i){
                System.out.print("- ");
                j=j+1;
            }
            if(counter%2==0){
                k=count-1;
                while(k>0){
                   System.out.print(k+" "); 
                   k=k-1;
                }
            }else{
                k=1;
                while(k<count){
                   System.out.print(k+" "); 
                   k=k+1;
                }
            }
            count=count+2;
            counter=counter+1;
            i=i-1;
        }
    }
}

您可以删除&#34; - &#34;之后的空格和数字,如果你想。我刚添加它们以使输出看起来很好。我的意思是System.out.print("- ")行可以写成System.out.print("-") and line System.out.print(k+" ") can be written as System.out.print(k). 不要忘记标记问题已解决。快乐编码:)

答案 1 :(得分:0)

试试这个。

int numberOfLines = 5;
int i = 0;
while (i < numberOfLines) {
    String hyphens = "---------".substring(0, numberOfLines * 2 - 1 - i);
    String numbers = "123456789".substring(0, i * 2 + 1);
    if (i % 2 == 0)
        numbers = new StringBuilder(numbers).reverse().toString();
    System.out.println(hyphens + numbers);
    ++i;
}