Using a foreach loop with custom object types in java

时间:2016-10-20 19:29:48

标签: java object for-loop foreach constructor

In advance I apologize for any mistakes in terminology, it's been a while since I've used java So I have the constructor

Planet[] stars = new Planet [500]

The aim is to call a draw() command on each object in stars. Previously I used the loop

for (int i = 0; i < 500;, i++)
 stars[i].draw(ss);

Although I have recently learnt of the foreach statement, if that is what the colon is called. So instead I try

for (int i : stars)
 stars[i].draw(ss);

Although upon compiling I receive the error "incompatible types: Planet cannot be converted to int"

I have tried typecasting but it will not allow that either.

Thanks for any help offered

1 个答案:

答案 0 :(得分:0)

Try this:

for (Planet planet : stars) {
   planet.draw(ss);
}
相关问题