| Author |
how can I print identity matrix
|
y bin
Greenhorn
Joined: Feb 18, 2004
Posts: 4
|
|
from the input: java Solematrix 4 4 is variable print out :1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 ------------------------------------ code: public class Solematrix{ public static void main(String[] args){ int n=0; n= Integer.parseInt(args[0]); int[][] m=new int[n][n]; for(int i=1; i<=n; i++){ for(int j=1; j<=n; j++){ if(i==j) m[i][j]=1; else m[i][j]=0; } } for(int i=1; i<=n; i++){ if(i!=1){System.out.print("");} for(int j=1; j<=n; j++){ System.out.print(m[i][j]+", "); } } } } ------ tcf% javac Solematrix.java tcf% java Solematrix Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at Solematrix.main(Compiled Code) ----- I dont understand what the exception say anybody can help or modify for the code thanks a lot brokeybin
|
 |
Nathaniel Stoddard
Ranch Hand
Joined: May 29, 2003
Posts: 1258
|
|
The exception is saying that you are using an index to an array that is invalid (it is out of bounds). The problem is that you are iterating over the elements of you array starting with 1 and ending with 4. Since arrays in Java are indexed starting at 0, a 4-element array will have indexes 0,1,2 and 3. When you try and set/retrieve index 4, you get the exception you are seeing. In the future, you should check the API docs to view a description of the exception when you see one you don't fully understand.
|
Nathaniel Stodard<br />SCJP, SCJD, SCWCD, SCBCD, SCDJWS, ICAD, ICSD, ICED
|
 |
 |
|
|
subject: how can I print identity matrix
|
|
|