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
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With