帕斯卡三角格式

Pascal's Triangle Formatting

我有一个程序终于可以打印帕斯卡三角形了。 无论出于何种原因,当它打印时,它都会像您假设的那样正确打印所有行,但是在每一行的末尾它应该只停在最后一整行。我举个例子。 而不仅仅是这个:

Enter the row number up to which Pascal's triangle has to be printed: 4
Rows to print: 4
1
11
121
1331
14641

它打印这个:

Enter the row number up to which Pascal's triangle has to be printed: 4
Rows to print: 4
1
11
1211
1331211
14641331211

最后那些额外的花絮不应该在那里。我不知道为什么会有。非常感谢任何帮助。

"Yes, it is supposed to use recursion, and no, I can't change that."

这是我的代码:

import java.util.Scanner;

public class pascalsTriangle {
    public static int rows;
    public static String list = "";
    public static String line = "1";

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the row number up to which Pascal's triangle has to be printed: ");
        rows = scan.nextInt();
        System.out.println("Rows to print: " + rows);
        scan.close();
        if (rows == 1)
            System.out.println("1");
        else {
            System.out.println(print(1, rows));
        }
    }

    public static String print(int largest, int row) {
        if (row < 1)
            return "1";
        else{
            list = print(1, row - 1) + "\n" + curLine(row, 0, 1);
        }
        return list;
    }

    public static String curLine(int n, int k, int last) {
        if(n > k && n != 0){
            line = Integer.toString(last) + curLine(n, k + 1, last*(n - k)/(k + 1));
        }
        return line;
    }
}

当您的程序移动到将三角形的下一行放在一起时,您的字符串变量 line 需要重置回 "1"。发生的事情是,当您的程序移动到下一行时,line 仍然是前一行数字,并且它在上面添加了三角形。请注意最后一行的 "extra tidbit":14641'331211' 如何与它上面的行匹配:1'331211'

或者,您可以通过更改行来使用子字符串解决此问题:

list = print(1, row - 1) + "\n" + curLine(row, 0, 1);

收件人:

list = print(1, row - 1) + "\n" + curLine(row, 0, 1).substring(0,row+1);

这将完全解决您的问题