循环的对象数组

时间:2011-12-22 20:22:16

标签: java arrays object for-loop

public class Team {
    public int health;
    public int x;
    public int conflict;

}

public class Test extends Activity {
    Team enemy[] = new Team[50];
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            for(int i =0; i<enemy.length; i++){
            enemy[i].health = 0;
            enemy[i].x = -100;
            enemy[i].conflict = 0;
            }
        }
}

使用for循环我的游戏崩溃,没有for循环运行。我究竟做错了什么?谢谢你提前帮忙!

4 个答案:

答案 0 :(得分:7)

创建数组时:

Team enemy[] = new Team[50];

所有条目均为null。您需要在循环中初始化数组的每个元素:

for(int i =0; i<enemy.length; i++){
    enemy[i] = new Team(); // <-- added
    enemy[i].health = 0;
    enemy[i].x = -100;
    enemy[i].conflict = 0;
}

答案 1 :(得分:0)

您忘记实例化enemy[i]

执行以下操作

Team enemy[] = new Team[50];
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    for(int i =0; i<enemy.length; i++){
      enemy[i] = new Team();
      enemy[i].health = 0;
      enemy[i].x = -100;
      enemy[i].conflict = 0;
    }
}

答案 2 :(得分:0)

您需要在循环的每次迭代中创建一个新的Team对象

for(int i =0; i<enemy.length; i++){
        enemy[i] = new Team();
        enemy[i].health = 0;
        enemy[i].x = -100;
        enemy[i].conflict = 0;
        }

答案 3 :(得分:0)

你从来没有初始化敌人的元素。

enemy[i] = new Team();

enemy[i].health = 0;
enemy[i].x = -100;
enemy[i].conflict = 0;