2015-04-20 18 views
2

我一直在嘗試不同的變化for循環和不知道如何使這些模式:在Java中使用循環的模式不同的變化

模式

1 
121 
12321 
1234321 

我的代碼如下,但不像上面的例子那樣工作。

for (int i = 1 ; i <= rows ; i++) { 
    for (int j = (rows + 1 - i) ; j > 0 ; j--) { 
     System.out.print(j); 
    } 
    System.out.print("\n"); 
} 
+4

嘗試寫下來你的英語怎麼會有人指示做嬰兒步驟。例如,如何解釋如何構建第4行? – RobAu

+0

a.k.a.僞代碼,如http://en.wikipedia.org/wiki/Pseudocode – user2314737

回答

1

試試這個:它可能看起來太多的循環,但是卻又很容易理解和有效的。

public static void main(String[] args) { 
    int rows=5; 
    int i,j; 
    for(i=1;i<=rows;i++) 
    { 
     /*print left side numbers form 1 to ...*/ 
     for(j=1;j<i;j++) 
     { 
      System.out.printf("%d", j); 
     } 


     /*Print the middle number*/ 
     System.out.printf("%d", i); 


     /*print right numbers form ... to 1*/ 
     for(j=i-1;j>0;j--) 
     { 
      System.out.printf("%d", j); 
     } 
     System.out.println(""); 
    } 

} 
6

您的代碼只打印每行的後綴,您缺少爲每行寫12....i
另外,循環應該從i開始,而不是從rows-i+1開始。

for (int i = 1 ; i <= rows ; i++) { 
    //add an inner loop that prints the numbers 12..i 
    for (int j = 1 ; j < i ; j++) { 
     System.out.print(j); 
    }  
    //change where j starts from 
    for (int j = i ; j > 0 ; j--) { 
     System.out.print(j); 
    } 
    System.out.println(""); //to avoid inconsistency between different OS 
} 
4

首先注意11 * 11 = 121,111 * 111 = 12321等等。

然後使用10 Ñ - 1是一個數字,包含n個9的,所以(10 Ñ - 1)/ 9由n個1的。

所以我們得到:

int powerOfTen = 1; 
for (int len = 0; len < 5; len++) 
{ 
    powerOfTen = powerOfTen*10; 
    int ones = (powerOfTen-1)/9; 
    System.out.println(ones*ones); 
} 
+2

如果我是你的教授,我想要一個證明,這給出了正確的模式。 –

+2

只適用於'len <5'!如果他想把'6'輸出,你會得到錯誤的值。 – Loki

+0

@DavidWallace好點,看起來對n> 5不起作用。 – Maroun

3

代碼說明了一切!

public static void main(String[] args) { 
    String front = ""; 
    String back = ""; 
    int rows = 5; 
    for (int i = 1; i <= rows; i++) { 
     System.out.println(front+i+back); 
     front += i; 
     back = i + back; 
    } 
} 
+1

只是迭代'i',而不是引入一個額外的變量,而不是實際使用的,而不是作爲迭代索引? –

+0

@DavidWallace按照你的建議進行更改。謝謝! – iamprem

1
int n=0; 
for(int m =0; m<=5; m++){ 
    for(n= 1;n<=m;n++){ 
     System.out.print(n); 
    } 

    for(int u=n;u>=1;u--){ 

     System.out.print(u); 
    } 
    System.out.print(""); 
}