• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to initialize multidimentsional array just after declaration?  RSS feed

 
Winston Liek
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried this:



I also tried this:



but I get an error
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Winston,

For future reference, it's helpful if you post the actual error you're getting.

Anyway, when you initialize an array, you either give it a size or you give it initial values. Not both.
 
Amir Al Take
Greenhorn
Posts: 15
Java Mac Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan has the right answer. So in your case you could initialize it like this:

If you would have same names and you would like to add them to all elements of multidimensional array you can use loop to do that.
 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amir Al. wrote:Stephan has the right answer. So in your case you could initialize it like this:

f[0][0] = "Harry";
f[0][1] = "Hairy";

No he couldn't. An array declared aswould be an array of one String array and that String array would have one element.

So would cause an ArrayIndexOutOfBoundsException.
 
Amir Al Take
Greenhorn
Posts: 15
Java Mac Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stuart A. Burkett wrote:
Amir Al. wrote:Stephan has the right answer. So in your case you could initialize it like this:

f[0][0] = "Harry";
f[0][1] = "Hairy";

No he couldn't. An array declared aswould be an array of one String array and that String array would have one element.

So would cause an ArrayIndexOutOfBoundsException.




Sorry it was my typo. I fixed the answer.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!