-3

My code is

Scanner sc = new Scanner(System.in);
int v=sc.nextInt();
int s=sc.nextInt();
int[][] n = new int [v][s];
for (int i=0; i<n.length; i++) {
    for (int j=0; j<n[v].length-1; j++) {
        n[i][j]=sc.nextInt();
    }
}
System.out.print(n[v][s]);
System.out.println();

When I want to compile it, the terminal prints out:

java.lang.ArrayIndexOutOfBoundsException: 4
at Plevel.main(Plevel.java:13)

Can somebody please tell me what am I doing wrong?

Tom
  • 16,842
  • 17
  • 45
  • 54
  • 1
    This `new int [v][s]` and this `n[v].length` can't work together. The size number of an array isn't a valid index itself. – Tom Dec 16 '16 at 13:15

2 Answers2

1

I suppose the error is here:

System.out.print(n[v][s]);

an array is indexed from 0 to v-1 and from 0 to s-1

if you have an array 3x3, its displayed like this:

v[0]s[0] v[0]s[1] v[0]s[2]
v[1]s[0] v[1]s[1] v[1]s[2]
v[2]s[0] v[2]s[1] v[2]s[2]

so if you want to get the last element, you should write:

System.out.print(n[v-1][s-1]);
RetteMich
  • 125
  • 1
  • 9
0
 Scanner sc = new Scanner(System.in);
    int v=sc.nextInt();
    int s=sc.nextInt();
    // V variable becomes row and S variable come column, since you already know row length and column length you can use same for looping
    int[][] n = new int [v][s];

    for (int i = 0; i < v; i++) {
        for (int j = 0; j < s; j++) {
            n[i][j] = sc.nextInt();
        }
    }

    // If you want to print last value
    System.out.print(n[v-1][s-1]);

Array index start with 0 hence when you have array size 3, you can have index 0,1,2. If you use 3 as index then it will throw exception which you posted on your query

Nagaraddi
  • 269
  • 2
  • 7