-5

我想使用循环缩短我的代码。例如,我的游戏中有 5 个僵尸。所以我想我可以做到这一点

Image zombie;
for(int i = 0; i < 5; i++){
if (zombie.getZombieRect().intersects(zombie + i + .getZombieRect())) {
}}

为什么不能这样做?将 i 添加到僵尸的末尾。僵尸是一个形象。其他变量是zombie1、zombie2 等。感谢大家的帮助。

4

3 回答 3

8

这就是数组的用途:

Zombie zombies[] = {zombie, zombie1, zombie2, zombie3, zombie4};
for (int i = 0; i < zombies.length; i++) {
    if (zombie.getZombieRect().intersects(zombies[i].getZombieRect())) {

    }
}
于 2013-07-23T19:08:58.100 回答
1

要回答这个问题,

zombie + i

是编译时错误,因为 java 不允许 Image 对象与“+”运算符中的 int 结合使用。

于 2013-07-23T19:16:34.957 回答
1

Make an Array of Objects and then u can call them by using zombie[i] etc whatever you want to do. The thing of adding you are trying to do is suitable in case of strings only "zombie"+i; etc.

于 2013-07-23T19:12:46.767 回答