This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach 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 | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how can I print identity matrix " Watch "how can I print identity matrix " New topic

how can I print identity matrix

y bin

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
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++){
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
System.out.print(m[i][j]+", ");
tcf% javac
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
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.

I agree. Here's the link:
subject: how can I print identity matrix
Similar Threads
program correction
Im having problems with writing this program :(
LinearProgramming in Java
can any one explain Two -Dimensional Arrays (code)
help me to solve this assignments..