Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java Exception array
hi..
The string is
String [][] array1 = new String[][]{{"aaaa", "bbbb"},{"aaaa"," cccc"," dddd"," eeee"},{"aaaaa", "fffff", "gggg"}};
 
I want to display the elements as
aaaa, bbbb
aaaa,cccc
aaaa,dddd
aaaa,eeee
aaaaa,fffff
aaaaa,gggg
 
The following code
for (int row1=0;row1<=array1.length;row1++){
           for  ( int cols=0 ;cols<array1[row1].length ;cols++){
                      System.out.println(array1[0][0] +" "+ array1[row1][cols+1]);
}
 
}
gives me output as aaaa bbbb
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
 
Please suggest me what I should do to get the prefered output..Any help will be appreciated ...
Posted 7-Feb-13 23:17pm
pari2268
Edited 7-Feb-13 23:52pm
v2
Comments
Orcun Iyigun at 8-Feb-13 4:26am
   
I think your array specification is wrong for a multidimensional array... Don't you get an error on it? The elements seems ambiguous..
I think example usage should be:
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
{ "five", "six" } };

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

You are stepping outside of the array, change it to this;
 
for (int row1=0;row1<array1.length;row1++) {
   for (int cols=1 ;cols<array1[row1].length ;cols++) {
      System.out.println(array1[0][0] +" "+ array1[row1][cols]);
   }
}
 

/Fredrik
  Permalink  
v2
Comments
pari2 at 8-Feb-13 7:09am
   
thank you Fredrik Bornander..:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 DamithSL 265
1 CPallini 235
2 OriginalGriff 233
3 Maciej Los 175
4 George Jonsson 170
0 OriginalGriff 5,305
1 DamithSL 4,382
2 Maciej Los 3,760
3 Kornfeld Eliyahu Peter 3,470
4 Sergey Alexandrovich Kryukov 2,901


Advertise | Privacy | Mobile
Web04 | 2.8.141216.1 | Last Updated 8 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100