-1

Actually I am solving one of the SPOJ problem. In this I am comparing two adjacent array elements and storing greater element in previous row index with its addition. Here is my code-

import java.util.Scanner;

/**
 * Created by Sainath on 15-08-2016.
 */
public class SIT {
    public static void main(String[] args) {
        int a;
        int b[][];
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        while (n != 0) {
            a = sc.nextInt();
            b = new int[a][a];
            for (int i = 0; i<a; i++) {
                for (int j = 0; j<=i; j++) {
                    b[i][j] = sc.nextInt();
                }
            }
            for (int i=a; i>1; i--) {
                for (int j=1; j<a; j++) {
                    if (b[i][j] >= b[i][j+1])
                        b[i-1][j] = b[i-1][j] + b[i][j];
                    else
                        b[i-1][j] = b[i-1][j] + b[i][j+1];
                }
            }
            System.out.println(b[0][0]);
            n--;
        }
    }
}

I am getting "ArrayIndexOutOfBoundsException" exception at line 22.

2 Answers2

0

Try running second for loop till a-2 instead of a-1.

 for (int i=a; i>1; i--) {
            for (int j=1; j<a-1; j++) {    try a-1 instead of a
                if (b[i][j] >= b[i][j+1])
                    b[i-1][j] = b[i-1][j] + b[i][j];
                else
                    b[i-1][j] = b[i-1][j] + b[i][j+1];
            }
        }

Because you are using j+1.

Kaushal28
  • 5,377
  • 5
  • 41
  • 72
0

Change you code from

int n = sc.nextInt(); while (n != 0) {

to

while (sc.hasNext()) {

The reason is that, to check if scanner has something in it, you have to use hasNext() method and to consume an int from scanner you can use nextInt() method. Since you are using nextInt() method to check if scanner has something in it, its checking the scanner as well as consuming first element from the scanner. Try this out and let me know if you need more explanation.

sri
  • 61
  • 4