java - Pascal 三角程序中的 ArrayIndexOutOfBounds 问题

标签 java recursion pascals-triangle

我正在开发一个 Java 作业程序,我需要使用递归来填充帕斯卡三角形,然后打印给定的三角形线。

一切都编译得很好,但我遇到了 ArrayIndexOutOfBound 异常的问题。

pTTest 类中对 main(第 30 行)的堆栈跟踪来自 populateT 方法中 pasTriangle 的第 80、87、92 行。很明显这里出了问题。有人知道这里出了什么问题吗? 请参阅下面我的代码:

//*******************************************************************************************************************************************************************************************
// pasTriangleTest.java
//
// 
// Tests the pasTriangle class by creating a few Pascal's Triangles of different size as pasTriangle objects. Then calls the getLine method of pasTriangle class to print some of the lines
// of the triangles. Tests include printing lines in the triangle, as well as trying to print the first line and non-existent lines of some triangles.
// Anticipated exception (ArrayIndexOutOfBounds exception), occurring if line (row) outside of array is attempted to be accesed, is handled.
//
//
//
//*******************************************************************************************************************************************************************************************


public class pTTest


{

    public static void main (String [] args)
    {



        pasTriangle T1 = new pasTriangle(1);
        pasTriangle T2 = new pasTriangle(9);
        pasTriangle T3 = new pasTriangle(3);
        pasTriangle T4 = new pasTriangle(5);            //Triangle with only one line created (so not a triangle); test for condition size == 1.

        T1.populateT(0, 0);
        T2.populateT(0, 0);
        T3.populateT(0, 0);
        T4.populateT(0, 0);



        T1.getLine(1);
        T2.getLine(4);
        T2.getLine(9);                  //Test for last line.
        T3.getLine(1);                  //Test for first line.
        T3.getLine(2);
        T4.getLine(1);                  //Test for first line.


    }   



}

//*******************************************************************************************************************************************************************************************
// pasTriangle.java
//
// 
// Represents Pascals's triangle. Determines the values on any given line of the triangle, given that each value on the inside of the triangle is the sum of the two values above it.
// 
// Constructor recursively creates a Pascal's triangle given a certain size (number of lines the triangle contains).
//
//
//*******************************************************************************************************************************************************************************************

public class pasTriangle
{

    private int size, row, col;                                                         //Represents the number of lines the triangle has.

    private int [][] pTriangle;                                                 //2-D array to hold int values of triangle





    /* ****************************************************************************************************************************************************

            Constructor creates a 2D array to hold the Pascales triangle. Note the number of numbers on each line is the same as the number of lines in
            the triangle, so size can be used for both values. Calls populateT method to populate the triangle.

        ***************************************************************************************************************************************************/



    public pasTriangle(int size)
    {
        this.size = size;

        pTriangle = new int[size][size];


    }       


        /* ****************************************************************************************************************************************************

            Method which populates the Pascal's Triangle recursively. Note case where size = 1, recursion does not occur since only 1 integer can be added
            to array.
            Also note base case where base of triangle is reached and recursion stops.
            Also note cases for first and last value of each line (row).

            Appropriate values added to each index according to conditions.


        *********************************************************************************************************************************************************/
    public void populateT(int row, int col)
    {


        if(size == 1)
        {
            pTriangle[0][0] = 1;
        }


        else if(size > 1)
        {
            if (col==0 && row == 0)                                                             //First value.      
            {
                pTriangle[row][col] = 1;
            }


            else if (col == 0 || col == pTriangle[row].length-1)
            {
                pTriangle [row][col] = 1;                                                       //1 Set for first value in each line and last value in each line.

            }

            else if(row > 1 && col != pTriangle[row].length-1)                      //Values in between first and last calculated from the two above them, to left and right.
            {
                pTriangle[row][col] = (pTriangle[row-1][col-1]) + (pTriangle[row-1][col+1]);

            }


            if (col < pTriangle[row].length)    //Move over and give values to indexes recursively until end of row is reached
            {
                populateT(row, col+1);          //Recursive call here.

            }

            else if (col >= pTriangle[row].length && row < pTriangle.length)    //If end of row is reached and number of rows is not exceeded.
            {   
                col = 0;                                        //Col reset.
                populateT(row+1, col);                          //Move to next row as long as base of triangle is not exceeded, recursive call again here.
            }


        }


    }



    /* ***********************************************************************************************************************************************

            Prints a string containing the values on a given line of the pasTriangle. Note 1 is subtracted from lineNumber to get correct index.

        ***********************************************************************************************************************************************/


    public String getLine(int lineNumber)
    {
        lineNumber = lineNumber - 1;
        String result = "";

        for(int biz = 0; biz < pTriangle[lineNumber].length; biz++)
        {
            result += Integer.toString(pTriangle[lineNumber][biz]);

        }

        System.out.println(result+"/n");

        return result;

    }

}

最佳答案

我想我知道答案。

我发现代码片段的 else if 链中很可能缺少 else:

... else if(row > 1 && col != pTriangle[row].length-1)                      //Values in between first and last calculated from the two above them, to left and right.
            {
                pTriangle[row][col] = (pTriangle[row-1][col-1]) + (pTriangle[row-1][col+1]);

            }

// else missing
=========>  if (col < pTriangle[row].length)    //Move over and give values to indexes recursively until end of row is reached
            {
                populateT(row, col+1);          //Recursive call here.

            } ...

我插入了else,程序成功启动并打印以下内容:

1/n
000000000/n
000000000/n
100/n
000/n
10000/n

希望能有所帮助。

关于java - Pascal 三角程序中的 ArrayIndexOutOfBounds 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31869861/

相关文章:

algorithm - 给定一个整数 z<=10^100,找到包含 z 的帕斯卡三角形的最小行

Java Minimax Alpha-Beta 修剪递归返回

c++ - 在 C++ 中居中 Pascal 的三角形输出

java - 具有未检查或不安全操作的实体 bean

java - 如何在 GWT 中检查时间戳的正则表达式?

php - 通过相关实体正确递归

使用递归计算更大数组中子数组的出现次数

java - 二项式系数数组

java - 如何替换已弃用的@MockClass?

java - Cassandra ,赫克托耳 :how to retrieve specific set of columns for specific keys from a column family in 1 call?