I was writing a simple Java program to input a matrix and then display it using 2-dimensional arrays. I used the same logic which I had previously used for the same program in C. But it isn't working. It goes on taking taking values until the index goes out of bound and then displays an error :
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at apples.main(apples.java:136)"
The line 136 is: a[i][j] = mad.nextInt(); in bold below
Are there other methods of doing this. The user has to give the input for the matrix and then it should be displayed.import java.util.Scanner;
class apples{
public static void main(String args[]){
int a[][] = new int[4][4];
int m,n;
Scanner mad = new Scanner(System.in);
System.out.println("Enter the order");
m = mad.nextInt();
n = mad.nextInt();
System.out.println("Order is " + m + "x" + n);
System.out.println("Enetr the elements");
for(int i=0;i<m;i++){
for(int j=0;i<n;j++){
a[i][j] = mad.nextInt();
}
}
System.out.println("The matrix is");
for(int i=0;i<m;i++){
for(int j=0;i<n;j++){
System.out.println(a[i][j]);
System.out.println("\t");
}
System.out.println();
}
}
}
Thank you,


LinkBack URL
About LinkBacks
Reply With Quote