简体   繁体   中英

Java Index Out Of Bounds Error on Pascal Triangle

I have to create a Pascal Triangle and when I run the code, it gives me an Array out Of Bounds Error. Please Help. I guess I have used a good logic but am unable to get the result.

import java.io.*;
public class Question_4
 {
 public static void main (String[] args)throws IOException
  {
      System.out.println("Enter the value of N");
      InputStreamReader x = new InputStreamReader (System.in);
      BufferedReader y = new BufferedReader (x);
      int n = Integer.parseInt (y.readLine ());
      int ar [] [] = new int [n] [(2*n)-1];
      int previous = 0;
      int next = 0;
      int se = 0;
      for (int row = 0 ; row<n ; row++)
       {
         se = (n - row) - 1;
         for (int column = 0 ; column < ((2*n)-1) ; column ++)
          {
              try
               {
                 previous = ar [row-1] [column+1];
                 next = ar [row-1] [column +3];
                }
              finally
               {
                 if (column < se)
                      ar [row] [column] = 0;
                 else if (column > (n-se))
                      ar [row] [column] = 0;
                 else if (row == 0 || row == 1)
                      ar [row] [column] = 1;
                 else
                      ar [row] [column] = (previous + next);
                }
            }
        }
      for (int i = 0;i<n;i++)
       {
           for (int j = 0; j<((2*n)-1);j++)
            System.out.print (ar [i] [j]);
           System.out.println ();
        }
    }
}

The problem within the this line:

previous = ar [row-1] [column+1];

At the first time of the outer loop, the row value is 0 , so 0 - 1 is -1 , which is invalid position the array.

You declared this array:

int ar [] [] = new int [n] [(2*n)-1];

Then you have this loop:

for (int column = 0 ; column < ((2*n)-1) ; column ++)

Which means that column will at some point be equal to the index of the last cell in ar[][]. And in your loop you call:

previous = ar [row-1] [column+1];
next = ar [row-1] [column +3];

That is why you get indexOutOfBoundsException.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM