猿问

递归方法导致 java.lang.StackOverflowError

我正在尝试创建帕斯卡三角形,以及以下行:


return pascalTriangle(row-1, col-1) + pascalTriangle(row-1, col);

在返回帕斯卡三角形中的值的递归方法中,原因int


Exception in thread "main" java.lang.StackOverflowError

它只打印一行,然后为其他行抛出异常。我需要修复什么,这样它就不会引发任何异常,并形成帕斯卡三角形?这是我的代码:1


import java.util.Scanner;


/**

 * This program takes n input from the user, and forms

 * Pascal's Triangle in n number of rows that the user entered.

 */

public class DD_PascalsTriangle {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter an integer: ");

        // the number of rows created in the Pascal's Triangle

        int n = scanner.nextInt();

        // print Pascal's Triangle

        printTriangle(n);

    }


    /**

     * @param row rows in Pascal's Triangle

     * @param col columns in Pascal's Triangle

     * @return values in the Pascal's Triangle

     */

    private static int pascalTriangle(int row, int col) {

        if (col == 0 || col == row)

            // base case

            return 1;

        else

            // create the values in Pascal's Triangle

            return pascalTriangle(row-1, col-1) + pascalTriangle(row-1, col);

    }


    /**

     * @param n the input from the user, aka the n

     *          number of rows in Pascal's Triangle

     */

    private static void printTriangle(int n) {

        for (int row = 0; row < n; row++) {

            for (int col = 0; col < n; col++) {

                System.out.println(pascalTriangle(row, col) + " ");

            }

            System.out.println();

        }

    }

}


慕丝7291255
浏览 130回答 2
2回答

犯罪嫌疑人X

看起来你的代码正在进入一个无限循环,因为你对内部循环有一个错误的条件。内部循环正在迭代并填满堆栈内存,最终超过 JVM 分配的数量。为了避免这种堆栈溢出错误并完善帕斯卡三角形的形状,您只需添加一个额外的循环并更改内部循环的条件即可。public static void printTriangle(int n) {&nbsp; &nbsp; for (int row = 0; row < n; row++) {&nbsp; &nbsp; &nbsp; &nbsp; //Added Spacer loop for getting perfect shape for pascal triangle&nbsp; &nbsp; &nbsp; &nbsp; for (int spacer = n; spacer > row; spacer--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" ");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for (int col = 0; col <= row; col++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(pascalTriangle(row, col) + " ");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }}

守着一只汪

将第二个循环更改为循环访问 而不是 。rownpublic static void printTriangle(int n) {&nbsp; &nbsp; for (int row = 0; row < n; row++) {&nbsp; &nbsp; &nbsp; &nbsp; for (int col = 0; col <= row; col++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(pascalTriangle(row, col) + " ");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Python
我要回答