帕斯卡三角形格式



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

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

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

"是的,它应该使用递归,不,我不能改变它。

这是我的代码:

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仍然是前一行数字,它会将三角形添加到该行上。请注意最后一行的"额外花絮":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);

这将完全解决您的问题

最新更新