Danny Gomes Danny Gomes - 3 months ago 36
Java Question

ArrayIndexOutOfBoundsException when setting values in the same array

Hello I've tried looking around and I can't find an answer to my problem. I get the error mentioned above when I do this.

int n = in.nextInt();
int[][] num = new int[1][n];

public static void preencherVetor(int[][] v) {
System.out.println("Introduza os valores.");
for (int i = 0; i < v[0].length; i++) {
v[0][i] = in.nextInt();
v[1][i] = v[0][i];

When it gets to v[1][i] = v[0][i]; it gives me an ArrayIndexOutOfBoundsException and I can't understand why. Both arrays have the same length and I want to make a 2 line array both with the same values. The array goes in as a parameter and n does have a value already so length is set.


Change this line

int[][] num = new int[1][n];


int[][] num = new int[2][n];

Since, there are supposed to be two rows in the matrix.