Java Reference
In-Depth Information
Solution 55: Creationism
This is a trick question. The program looks as though it ought to print 100 , but it doesn't print
anything, because it doesn't compile. If you tried to compile it, you may have found the compiler
diagnostics to be less than helpful. This is what javac prints:
Creator.java:4: not a statement
Creature creature = new Creature();
^
Creator.java:4: ';' expected
Creature creature = new Creature();
^
A local variable declaration looks like a statement but technically speaking is not; it is a local
variable declaration statement [JLS 14.4]. The syntax of the language does not allow a local
variable declaration statement as the statement repeated by a for , while , or do loop [JLS 14.12-14].
A local variable declaration can appear only as a statement directly within a block. (A block is
a pair of curly braces and the statements and declarations contained within it.)
There are two ways to fix the problem. The obvious way is to place the declaration in a block:
for (int i = 0; i < 100; i++) {
Creature creature = new Creature();
 
 
Search WWH ::




Custom Search