2013-10-02 126 views
-3

非常簡單,但我似乎無法弄清楚,我只需要將while循環轉換爲do-while。目標是打印1-9和9-1,例如「1,22,333,4444」等。謝謝你,如果你幫我!雖然做while循環的同時做

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); 
} 
+1

1)爲了更好地幫助越早,張貼[SSCCE(http://sscce.org/)。 2)對代碼塊使用一致的邏輯縮進。代碼的縮進旨在幫助人們理解程序流程。 3)源代碼中的單個空白行是* always *就足夠了。 '{'之後或'}'之前的空行通常也是多餘的。 –

+1

您錯過了第二個「do」聲明。第二個while語句實際上是一個while循環,它不執行任何代碼,因爲變量的內容沒有改變,它等價於「while(true);」 (也似乎並沒有改變d的值,y也沒有定義) –

+0

分號太多 – pamphlet

回答

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); 
    } 
} 
+0

我很欣賞它,但我確實說過,我不希望你爲我做這件事。我是少數意識到我需要知道如何去做的人之一。我不明白的是,我只是嘗試了一些與我所知道的完全相同的東西,但它並不奏效,它無限計算。在錯誤的地方支架可能導致了這種情況? – user2836944

+0

你的無限循環肯定來自這裏: while(d <= c); 你有一段時間什麼都不做,所以條件永不改變。如果d <= c,它將是無限的...... –

+0

現在有道理了。我感謝您的幫助。我知道這是一個微不足道的初學者錯誤,但每個人都從某處開始吧?隨着我學到更多東西,我一定會爲社區做出貢獻。再次感謝。 – user2836944

0

這是一個基本的用法:

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

應用它,因爲你需要。我們不能真的做你的功課。

+0

我理解並明白,我不指望你,我只是在右邊尋找指導方向。 – user2836944

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(); 
} 
0

當你想在無限循環中運行只需使用:

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

     } while (c < 10); 
    } while (true); 
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);