简体   繁体   English

为什么我的Pascal的Triangle Java代码无法正常工作?

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

My question has been recently put on hold, so I decided to ask it again. 我的问题最近被搁置了,所以我决定再问一次。

I have an assignment where my professor wants us to make Pascal's triangle on Java. 我有一个作业,我的教授希望我们在Java上绘制Pascal的三角形。 He provided us a completed Main class that is supposed to work and we have to use it. 他为我们提供了完整的,应该可以使用的Main类,我们必须使用它。 We do not have to edit the Main class. 我们不必编辑Main类。 The Main class is correct. Main类是正确的。 It calls for the method where we have to write in our code. 它要求我们必须在代码中编写的方法。 Also, I provided the correct output and the template of the Pascal class, which has the method I am supposed to fill in. 另外,我提供了正确的输出和Pascal类的模板,该模板具有我应该填写的方法。

Here is the main class: 这是主要的类:

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

My professor wants us to use his template of the Pascal class where we have to write in the code for the triangle method only. 我的教授希望我们使用他的Pascal类模板,在该模板中,我们只需要为三角方法编写代码。 This is the only area where we have to write code for the assignment. 这是我们唯一需要编写分配代码的区域。

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

The output should be this: 输出应该是这样的:

 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 

Here is my Pascal class code: 这是我的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};
 }
} 

My output: 我的输出:

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

Just return pt[n-1]; 只需return pt[n-1]; instead of a new empty array from the template (you are supposed to remove that line). 而不是模板中的新空数组(应该删除该行)。

With that, it works for me, your algorithm is correct. 这样,它对我有用,您的算法是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM