• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

how can I print identity matrix

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
The glass is neither half full or half empty. It is too big. But this tiny ad is just right:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic