转换while循环来做

时间:2013-10-02 14:56:36

标签: java

非常简单,但我似乎无法弄清楚,我只需要将while循环转换为do-while。目标是打印1-9和9-1,如“1,22,333,4444”等。谢谢你帮助我!

int y = 1;
int x = 1;
while (x < 10) {
    y = 1;
    while (y <= x) {
        y++;
        System.out.print(x + "");
    }
    System.out.println();
    x++;
}

int a = 9;
int b = 1;
while (a >=1) {
    b = 1;
    while (b<= a) {
        b++;
        System.out.print(a + "");
    }
    System.out.println();
    a--;
}

我的尝试打印1-9但是作为单个数字并且无限次运行,但是在第一次9之后不会打印任何内容。

int c = 1;
int d =1;
do { System.out.print(c +"");
c++;
System.out.println();
}
while (c<10);{
    y=1;
    while (d<=c);
}

5 个答案:

答案 0 :(得分:0)

这是一个基本用法:

x=1;
do{ 
    //hello
    x++; 
} while(x<=10); 

根据需要应用它。我们不能真正做你的功课。

答案 1 :(得分:0)

您想要的是嵌套do-while

int x = 1;

do {
   int p = 0;
   do {
      System.out.print(x); 
   }
   while(p < x)
   System.out.println();
   x++;
}
while(x < 10)

但是我应该在这里添加一个for循环会更有意义:

for(int x = 0; x < 10; x++)
{
    for(int p = 0; p < x; p++)
    {
        System.out.print(x);  
    }
    System.out.println();
}

答案 2 :(得分:0)

如果你想在无限循环中运行,只需使用:

    do {
        int c = 1;
        do {
            System.out.println(c);
            c++;

        } while (c < 10);
    } while (true);

答案 3 :(得分:0)

看起来我们正在做功课......

public class Test {
    public static void main(String[] args) {
        int c = 1;
        do { 
            int d =1;
            do{
                System.out.print(c);
                d++;
            } while (c>=d);
            System.out.println("");
        c++;        
        }
        while (c<10);
    }
}

答案 4 :(得分:0)

这将无限运行并打印您想要的字符串:

        StringBuilder result1= new StringBuilder();
    StringBuilder result2 = new StringBuilder();

    do
    {
        for(int i = 1; i < 10; i++)
        {
            for(int j = 0; j < i; j++)
            {
                result1.append(i);
            }
            result1.append(",");
        }

        for(int i = 9; i > 0; i--)
        {
            for(int j = 0; j < i; j++)
            {
                result2.append(i);
            }
            result2.append(",");
        }

        System.out.println(result1);
        System.out.println(result2);
    }while(true);
相关问题