我正在尝试创建Pascal的Triangle,并创建“ return pascalTriangle(row-1,col-1)+ pascalTriangle(row-1,col);”行。在返回帕斯卡三角形中的int值的递归方法中,导致线程“ 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: ");
int n = scanner.nextInt(); //the number of rows created in the Pascal's Triangle
printTriangle(n); //print Pascal's Triangle
}
/**
*
* @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) return 1; //base case
else return pascalTriangle(row - 1, col - 1) + pascalTriangle(row - 1, col); //create the values in Pascal's Triangle
}
/**
*
* @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();
}
}
}
答案 0 :(得分:1)
似乎您的代码将进入无限循环,因为您为内部循环保留了错误的条件 哪个调用和调用......填充堆栈内存比JVM分配的更多
为避免帕斯卡三角形的堆积溢出错误和完美形状,您只需添加一个额外的循环并更改内部循环的条件即可。
public static void printTriangle(int n){
for(int row = 0; 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();
}
答案 1 :(得分:0)
更改第二个循环以迭代到上一行而不是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();
}