簡體   English   中英

為什么我的Pascal的Triangle Java代碼無法正常工作?

[英]Why won't my Pascal's Triangle java code work?

我的問題最近被擱置了,所以我決定再問一次。

我有一個作業,我的教授希望我們在Java上繪制Pascal的三角形。 他為我們提供了完整的,應該可以使用的Main類,我們必須使用它。 我們不必編輯Main類。 Main類是正確的。 它要求我們必須在代碼中編寫的方法。 另外,我提供了正確的輸出和Pascal類的模板,該模板具有我應該填寫的方法。

這是主要的類:

 public class Main 
  {

  public static void main(String[] args) 
  {

    int n = args.length == 1 ? Integer.parseInt(args[0]) : 1;

    for (int i = 1; i <= n; ++i) 
    {
        int[] arr = Pascal.triangle(i);
        System.out.print((i < 10 ? " " : "") + i + ": ");
        for (int j : arr) 
        {
            System.out.print(j + " ");
        }
        System.out.println();
    }
 }
}

我的教授希望我們使用他的Pascal類模板,在該模板中,我們只需要為三角方法編寫代碼。 這是我們唯一需要編寫分配代碼的區域。

 public class Pascal 
 {
   public static int[] triangle(int n) 
   {
     //My code goes here
     return new int[]{0};
   }
 }

輸出應該是這樣的:

 1: 1 
 2: 1 1 
 3: 1 2 1 
 4: 1 3 3 1 
 5: 1 4 6 4 1 
 6: 1 5 10 10 5 1 
 7: 1 6 15 20 15 6 1 
 8: 1 7 21 35 35 21 7 1 
 9: 1 8 28 56 70 56 28 8 1 
 10: 1 9 36 84 126 126 84 36 9 1 

這是我的Pascal類代碼:

 public class Pascal
 {
   public static int[] triangle(int n) 
   {
   int [][] pt = new int[n+1][];

     for (int i = 0; i < n; i++) 
     {
     pt[i] = new int[i + 1];
     pt[i][0] = 1;//sets the position to 1
     pt[i][i] = 1;

      for (int j = 1; j < pt[i].length - 1; j++)
      {
       pt[i][j] = pt[i-1][j-1] + pt[i-1][j];
      }
 }
  return new int[]{0};
 }
} 

我的輸出:

 1: 0 
 1: 10 
 1: 20 
 1: 1 
 1: 0 
 1: 0 

只需return pt[n-1]; 而不是模板中的新空數組(應該刪除該行)。

這樣,它對我有用,您的算法是正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM