Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

object array compile error

 
Bob Joness
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i'm having compilation problems with this piece of code. The problem is with the 'x' in the lines arrayOfCars[x] = tempBuyCar; and System.out.println(arrayOfCars[x]);

i get the error 'cannot resolve symbol'. however if i replace the x with a number it compiles.

 
fred rosenberger
lowercase baba
Bartender
Posts: 12185
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This one is easy. since x is declared inside the "for" statment, it falls out of scope once you leave the loop. you don't have braces after your "for" statement so, the only line that is part of your loop is the "tempBuyCar" line. that is the ONLY line being run over and over.

so...

when you get to the arrayOfCars, x has fallen out of scope, thus the compiler can't resolve it.

do this:

and life should be good.
[ May 20, 2004: Message edited by: fred rosenberger ]
 
Bob Joness
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yep that fixed it. can't believe how simple it was.

cheers
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some beginners, and some folks with a bit of experience, like myself, always include opening and closing braces, with constructs such as for-loops and if-statements.

It's also a required/recommended practice by some coding syle guides, such as JavaRanch's style guide. The reasoning for this is that consistency is easier to read, less editing is involved if lines of code are added or removed, plus it becomes very obvious what code is associated with the construct.

Also, I strongly recommend that you make a practice of properly indenting your code, as this will strongly help in its readability.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic