Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to create an Array of Objects

Tags:

arrays

android

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

like image 683
Oli Black Avatar asked Dec 21 '22 11:12

Oli Black


2 Answers

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;
}
like image 104
A--C Avatar answered Feb 09 '23 22:02

A--C


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

like image 44
petey Avatar answered Feb 09 '23 21:02

petey