java - 无法让帕斯卡的三角递归程序工作--Java

标签 java recursion multidimensional-array runtime-error pascals-triangle

我正在尝试为作业编写一个程序。要求是递归地创建帕斯卡三角形,然后打印给定的行。然而,编译我的程序后,我收到几个 ArrayIndexOutOfBoundsExceptions。这是堆栈跟踪: java.lang.ArrayIndexOutOfBoundsException: 10 at pasTriangle.populateT(pasTriangle.java:79) at pasTriangle.populateT(pasTriangle.java:86) at pasTriangle.populateT(pasTriangle.java:86) at pasTriangle.populateT(pasTriangle.java:86) 在 pasTriangle.populateT(pasTriangle.java:86) 在 pasTriangle.populateT(pasTriangle.java:86) 在 pasTriangle.populateT(pasTriangle.java:86) 在 pasTriangle.populateT(pasTriangle. java:86) 在 pasTriangle.populateT(pasTriangle.java:86) 在 pasTriangle.populateT(pasTriangle.java:93) 在 pasTriangle.populateT(pasTriangle.java:86) 在 pasTriangle.populateT(pasTriangle.java:86) 在 pasTriangle .populateT(pasTriangle.java:86) 在 pasTriangle.populateT(pasTriangle.java:86) 在 pasTriangle.populateT(pasTriangle.java:86) 在 pasTriangle.populateT(pasTriangle.java:86) 在 pasTriangle.populateT(pasTriangle.java) :93)在pasTriangle.populateT(pasTriangle.java:86)在pasTriangle.populateT(pasTriangle.java:86)在pasTriangle.populateT(pasTriangle.java:86)在pasTriangle.populateT(pasTriangle.java:86)在pasTriangle。 populateT(pasTriangle.java:86)

有人知道我做错了什么吗?我已经尝试了一切,尤其是改变条件,但没有任何效果。这是我的代码:

    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 > 0 && size == 1 && row < size)
        {
            pTriangle[0][0] = 1;
        }


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


            else if (row != 0 && 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 != 0 && 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]);      
//Line 79, exception here.

            }


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

            }

            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.   
**//Line 93 Exception here.**
                populateT(row+1, col);  
            }


        }


    }



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

            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;

    }

}

{

public static void main (String [] args)
    {


        try{
        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.
        }
        catch(ArrayIndexOutOfBoundsException exception)
        {
            exception.printStackTrace();
        }
    }   



}

最佳答案

ArrayIndexOutOfoundsException似乎即将到来,因为此行允许递归以无效的 row 继续。索引。

else if (col >= pTriangle[row].length && row < pTriangle.length)

row变量可以是 pTriangle.length - 1 ,然后你调用populateT(row+1, col) ,路过pTriangle.length进入递归调用。然后,该递归调用最终会尝试访问无效的 row索引,导致异常。将其更改为 row < pTriangle.length - 1将解决立即异常问题。

其正上方的条件,row < pTriangle.length , 控制何时移至下一列,但这里不需要它;您没有修改 row在这里。

此外,当您匹配 row 时,您将需要停止列递归。 ,而不是当您匹配 row 的物理结尾时,所以两个条件都需要改变。更改if (col < pTriangle[row].length && row < pTriangle.length)if (col < row) ,和else if (col >= pTriangle[row].length && row < pTriangle.length)else if (col >= row && row < pTriangle.length - 1) .

在这些条件之上,代码中需要进行类似的更改来确定是否写入 1或添加上行中的相关数字。更改else if (row != 0 && col == 0 || col == pTriangle[row].length-1)else if (row != 0 && col == 0 || col == row)else if(row > 1 && col != 0 && col != pTriangle[row].length-1)else if(row > 1 && col != 0 && col != row) .

当您添加前一行的元素以写入非 1 时value,看来您添加了错误的元素。假设有效的数据结构如下所示......

[1][0][0][0]
[1][1][0][0]
[1][2][1][0]
[1][3][3][1]

您需要将上方和左侧的元素添加到正上方的元素中。更改(pTriangle[row-1][col-1]) + (pTriangle[row-1][col+1]);(pTriangle[row-1][col-1]) + (pTriangle[row-1][col]); 。 (col+1 更改为 col。)

如果您更改 getLine 中的输出代码添加空格,您将能够更好地验证您的号码。另外,println已经在参数后打印了一个新行,因此您不需要附加换行符(即 \n 而不是 /n )。

关于java - 无法让帕斯卡的三角递归程序工作--Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31883108/

相关文章:

java - 获取 xs :choice maxOccurs and minOccurs attributes with XSOM

c++ - 如何使用内联和递归?

java - String 到 Long 的转换在 C 和 Java 中不同,为什么?

Java - RunnableFuture 和 SortProcessor

haskell - 使用 Either 中断递归

java - 数组数组与多维数组的性能比较

C++ 正确释放具有底层连续内存的多维数组

java - 如何在Java中将列表的列表转换为二维数组

java - 如何访问 Netbeans 中的调用计数?

java - Mandelbrot 集的视觉表示