How to get rid of ArrayIndexOutOfBoundsException: 3 : <p>I am new in Java and try to understand how it works two dimensional arrays, and i encounter this erros. Thanks</p>

<p>public class Main {</p>

<pre><code>public static int n, m, a[][];
public static void main(String []args){

    Scanner sc=new Scanner(System.in);
    n=sc.nextInt();
    m=sc.nextInt();
    a=new int[n][m];
    int i,j,s=0;
    for (i=0;i&lt;n;i++)
     for ( j=0;j&lt;m;j++){
         a[i][j]=sc.nextInt();
     }

    for (i=0;i&lt;a.length;i++){
        for (j=0;j&lt;a[i].length;j++){
            if (a[i][j+1]&gt;a[i+1][j]) s=s+a[i][j+1];
            else s=s+a[i+1][j];
        }
    }
    System.out.println(s);
    sc.close();
}
</code></pre>

<p>}</p>
