Oli Black
Oli Black

Reputation: 441

Trying to create an Array of Objects

I have an object I am trying to put in an array list:

class PlayerScores {

String playerName;
int played=0;
int win=0;
int draw=0;
int loss=0;
int points=0;


void playerNameSet(String name){
    playerName=name;
}
void played(){
    played=played+1;
}
void win(){
    win=win+1;
    points();
}
void draw(){
    draw=draw+1;
    points();
}
void loss(){
    loss=loss+1;
}

void points(){
    points = (win*3)+draw;
}

}

and basically, when the user has chose how many players there are I want to initialize an Array of these objects but I am getting errors. Here is the code for initializing the array and then assigning names to the players as well.

the array has been defined at the begining of my code and is public so I can use it in different activities: "PlayerScores[] playersObjects;"

public PlayerScores[] makePlayerObjects() {
        playersObjects = new PlayerScores[players];
        for(int i = 0; i < players + 1; i++)
        {
            playersObjects[i].playerNameSet(name variable);
        }

    return playersObjects;
}

the error seems occur on the line where the name is being set but it is not to do with the name variable.

Any help would be massively appreciated, Thanks, Oli

Upvotes: 5

Views: 22288

Answers (3)

A--C
A--C

Reputation: 36449

You haven't actually set the objects in the Array. You first need to construct a PlayerScores object then you can access it.

public PlayerScores[] makePlayerObjects() {
        playersObjects = new PlayerScores[players];
        for(int i = 0; i < playersObjects.length; i++)
        {
            playersObjects[i] = new PlayerScores(); //make the object so we can access it
            playersObjects[i].playerNameSet(name variable);
        }

    return playersObjects;
}

Upvotes: 9

petey
petey

Reputation: 17140

you could also use a list.

 List<PlayerScores > myList = new ArrayList<PlayerScores>();
 for(int i = 0; i < players.size(); i++){
        myList.add(new PlayerScores().playerNameSet(thename));
 }

also note the .size() usage assuming players is a different array. if it is a int then forget the .size() part

Upvotes: 2

Blackbelt
Blackbelt

Reputation: 157457

for(int i = 0; i < players + 1; i++)

it will cause ArrayIndexOutOfBoundException, because array's index go from 0 to size -1

Upvotes: 1

Related Questions