有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

异常递归方法导致java。StackOverflowerr语言

我正在尝试创建Pascal三角形,以及直线:

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

在返回Pascal三角形中的int值的递归方法中,导致

Exception in thread "main" java.lang.StackOverflowError

它只打印一行1,然后对其他行抛出异常。我需要修正什么,这样它就不会抛出任何异常,并形成Pascal三角形?这是我的密码:

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

共 (2) 个答案

  1. # 1 楼答案

    似乎您的代码将进入一个无限循环,因为您对内部循环有一个错误的条件。内部循环迭代并填充堆栈内存,最终超过JVM分配的内存量

    为了避免堆栈溢出错误并完善Pascal三角形的形状,只需添加一个额外的循环并更改内部循环的条件

    public static void printTriangle(int n) {
        for (int row = 0; row < n; row++) {
            //Added Spacer loop for getting perfect shape for pascal triangle
            for (int spacer = n; spacer > row; spacer ) {
                System.out.print(" ");
            }
            for (int col = 0; col <= row; col++) {
                System.out.print(pascalTriangle(row, col) + " ");
            }
            System.out.println();
        }
    }
    
  2. # 2 楼答案

    将第二个循环更改为迭代到row,而不是n

    public static void printTriangle(int n) {
        for (int row = 0; row < n; row++) {
            for (int col = 0; col <= row; col++) {
                System.out.print(pascalTriangle(row, col) + " ");
            }
            System.out.println();
        }
    }