I have a homework assignment but I'm very new to Java and have been trying for the past two days to create an array of player objects, set the names and get the names.
But whatever I try I get errors. I've watched lots of tutorials and copied out exactly what they've done but it doesn't work. How do I correctly create the array and get/set the names?
I have a Game class and a Player class:
Game class -- one version:
Player[] players = new Player[3];
//All the tutorials I've seen show both these types of putting names in:
players[0] = new Player();
//followed by:
players[0].setName("name");
//or...
players[0] = new Player("human");
//my errors on both: unknown class 'players'...
//unexpected token... invalid method... etc etc
Gmae class - different version (using a method):
//for the homework, I'm expected to put it all into a method
//ideally I'd be using the setName method from the Players class (below)
//but that doesn't work here
void createPlayers(Player[] players) {
for (Player p : players) {
players[0] = new Player("human");
players[1] = new Player("Greg");
players[2] = new Player("Susan");
}
}
public static void main(String[] args) {
Game obj = new Game();
//I had to change Players[] to static to get a printout but it's not supposed
//to be static
//I tried these separately to check output
//I need to be able to get the name of a player
obj.createPlayers(players); //no output
for (Player pl : players) {
System.out.println("Name = " + pl); //null null null
}
System.out.println(obj.players[0]); //null
obj.player[0].getName(); //cannot resolve symbol 'player'
}
Game Class -- another version (putting everything in main):
public static void main(String args[]) {
Main game = new Main();
Player p0 = new Player("Jeff"); //it errored if I didn't put a name
Player p1 = new Player("Susan"); //but I need to be able to change names
Player p2 = new Player("Michael");
Player[] players = new Player[3];
players[0] = p0;
players[1] = p1;
players[2] = p2;
p2.setPName("Alan");
System.out.println(p2.getPName()); //output: null
Player class: features getters and setters which I would ideally be using to get and set the player names but I don't know how to make them work in my Game class.
private String name;
Player (String name) { this.name = name; }
public void setName(String name) { this.name = name; }
public String getName() { return name; }
A simple modification on your Game class gave me this, which pretty much does what you want to do:
public class Game {
void createPlayers(Player[] players) {
Player player1 = new Player();
player1.setName("human");
Player player2 = new Player();
player2.setName("Greg");
Player player3 = new Player();
player3.setName("Susan");
players[0] = player1;
players[1] = player2;
players[2] = player3;
}
public static void main(String[] args) {
Player[] players = new Player[3];
Game obj = new Game();
obj.createPlayers(players);
for (Player pl : players) {
System.out.println("Name = " + pl.getName());
}
}
}