0
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;
            }
        }
}

With the for loop my game crashes, without the for loop it run. What am I doing wrong? thanks for the help ahead of time!

1
  • 1
    -1 because some very simple debugging would have solved this one. Commented Dec 22, 2011 at 20:31

4 Answers 4

7

When you create the array:

Team enemy[] = new Team[50];

all the entries are null. You need to initialize each element of the array in your loop:

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You forgot to instantiate enemy[i]

Do the following instead

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;
    }
}

Comments

0

You need to create a new Team object each iteration of the loop

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

Comments

0

you never initialized the elements of enemy.

enemy[i] = new Team();

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.