Doubt for creating and working with class arrays in JAVA
I have a program with 2 classes. The player class that contains only the Attribute name:
public class player {
String name;
}
And I have the main class that has the function below and the call of the same in main
Public class Principal{
public static void setPlayers(int valor){
int i;
for(i=0;i<valor;i++){
player[] vetor = new player[valor];
vetor[i] = new player();
}
}
public static void main(String[] args) {
System.out.println("Insira a quantidade de jogadores de 1 a 4");
int n = 4;
}
}
Now the doubt, I created 4 players and want to put their name or take their names. What call should I make in main? I tried this one below and it says that the Vector does not exist
vetor[0].getName();
For the exercise I'm doing, I need to store an X amount of players and change / pick up their names. So I needed to manipulate the data of this Vector
1 answers
You have an array scope problem vetor
. Because it was created inside for
, it will only exist while for
is running and can only be accessed there as well.
Throwing the line player[] vetor = new player[valor];
out of the for
solves your problem of accessing it.
As for creating and manipulating a Player
, you need to create the access methods in the Player
class. The way it is today, without a getNome()
method, the compiler will complain that this method does not exists:
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
That done, you can do so within for
to create and name a Player
:
Player player = new Player();
player.setName("Joaquim");
vetor[i] = player;
To display the name of the newly created player, you could add the following line at the end of for
:
System.out.println(vetor[i].getNome());
* beware of the class name using only lowercase letters. Although technically valid, it is not good practice in Java. Instead of player
, your class should be called Player
.