Reputation: 13
The problem is at int [][]tam = new int [a][b]
. It's only that line. I am new to Java and coming from a C++ background.
//"Exercitiul" 3
Scanner input = new Scanner(System.in);//instructiune scanner
DataInputStream dis4 = new DataInputStream(System.in);
DataInputStream dis5 = new DataInputStream(System.in);
String st1 = null;
String st2 = null;
try{
System.out.println("Introduceti numarul de Randuri");
st1 = dis4.readLine();
System.out.println("Introduceti numarul de Coloane");
st2 = dis5.readLine();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
int a = Integer.parseInt(st1);
int b = Integer.parseInt(st2);
int [][]tam = new int[a][b];
System.out.println("Verificare " + tam[a][b]);
System.out.println("Introduceti Elementele Matricei ");
for (int m=0 ; m < tam.length ; m++)
for (int n=0 ; n < tam[i].length ; n++){
tam[m][n] = input.nextInt();//instructiune scanner
}
System.out.println("Matricea A: ");
for (int m=0 ; m < tam.length ; m++)
{ System.out.println();
for (int n=0 ; n < tam[i].length ; n++)
System.out.print(tam[m][n]+" ");
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Program.main(Program.java:95)
Upvotes: 0
Views: 121
Reputation: 691775
I think the problem is rather at the line
System.out.println("Verificare " + tam[a][b]);
tam is initialized as new int[a][b]
. This means its first index goes from 0 to a - 1, and its second index goes from 0 to b - 1. Array indices start at 0 in Java. So tam[a][b]
is indeed out of the bounds.
Upvotes: 1
Reputation: 18633
If an array a
has length n
, the elements are a[0]
through a[n-1]
.
In your case, you allocated tam
as an int[a][b]
and the bottom-right element of the matrix is tam[a-1][b-1]
.
Also I think you want m
as an index in your inner loop for (int n=0 ; n < tam[i].length ; n++)
instead of i
.
Upvotes: 3
Reputation: 7739
If that line is throwing the exception, it probably means that either a or b is <= 0. Check your input values.
Upvotes: 1