2013-12-08 29 views
0

我試圖打印這個模式,就像我在給出的代碼片段中顯示的那樣。但不知何故,我不知道我是如何將這個奇怪的輸出與所需的輸出一起出現的。如果你們可以幫忙我會很感激糾錯模式錯誤

/*2 6 12 20 30 42 
* 4 6 8 10 12 
* 2 2 2 2 
* 0 0 0 
* 0 0 
* 0 
* 
*/ 


public class patt { 
    static int ar[]={2,6,12,20,30,42}; 
    public static void pattern(){ 
     int y=0,x=0; 
     while(x<ar.length){ 
      int c[]=new int[6]; 

        if(x+1>=ar.length){ 
       break; 
      } 
      else{ 
      c[x]=ar[x+1]-ar[x]; 
      System.out.print(c[x]+" "); 
      ar[x]=c[x]; 
     } 
      x++; 
      } 
      System.out.println(); 



    } 


    public static void main(String args[]){ 
    patt ob=new patt(); 
    System.out.println("2 6 12 20 30 42"); 
for(int a=0;a<6;a++){ 
    ob.pattern(); 
} 
} 
} 

The output is as follows, 
2 6 12 20 30 42 
4 6 8 10 12 
2 2 2 2 30 
0 0 0 28 12 
0 0 28 -16 30 
0 28 -44 46 12 
28 -72 90 -34 30 

回答

1

你正在運行6次函數(作爲數組的長度)。 的問題是,你保持靜態數組中的變化,但然後運行以下條件:

if(x+1>=ar.length){ 
    break; 
} 

以上是精爲先運行。但在第一次運行後,應該有5個元素(在元素之間做出區別之後)。但是,您將始終以陣列的整個長度運行。這就解釋了爲什麼每行總是打印5個元素。 您的解決方案是定義另一個靜態數組,它是長度,然後在每次運行後減少該長度。 我添加了一個靜態長度變量,替換了上面列出的條件來查看它,而不是總是查看數組長度,並減少了每次運行時的變量。

public class patt { 
    static int ar[]={2,6,12,20,30,42}; 
    static int length=ar.length; 
    public static void pattern(){ 
     int y=0,x=0; 
     while(x<ar.length){ 
      int c[]=new int[6]; 

        if(x+1>=length){ 
       break; 
      } 
      else{ 
      c[x]=ar[x+1]-ar[x]; 
      System.out.print(c[x]+" "); 
      ar[x]=c[x]; 
     } 
      x++; 
      } 
      System.out.println(); 
     length--; 


    } 


    public static void main(String args[]){ 
    patt ob=new patt(); 
    System.out.println("2 6 12 20 30 42"); 
for(int a=0;a<6;a++){ 
    ob.pattern(); 
} 
} 
}