This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes how can I print identity matrix Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "how can I print identity matrix " Watch "how can I print identity matrix " New topic
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
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: how can I print identity matrix
 
Similar Threads
can any one explain Two -Dimensional Arrays (code)
Im having problems with writing this program :(
LinearProgramming in Java
program correction
help me to solve this assignments..