• Post Reply Bookmark Topic Watch Topic
  • New Topic

2D arrays  RSS feed

 
Adam Blais
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In class we're discussing how to declare and assign values to 2D arrays and how you can declare a certain number of rows and assign column values later on. Here is a sample of my code:



When trying to compile I get the error "array dimension missing" and the line d[0] = new int[] = {1}; highlighted.
This is the exact syntax that the prof is using. What's wrong with it?
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try it this way:


{3,4,5} is an array initializer, but it isn't a complete expression that can be assigned. You can only use it in an array declaration
int d[] = {3,4,5};
or an array creation expression
new int[]{3,4,5}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to be explicit: the syntax

d[0] = new int[] = {1};

is wrong; there's no such syntax in Java. That second equals sign should just be deleted. "new int[]{...}" is a single expression that creates an int array and initializes its contents.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!