Doubt to create and work with class array in JAVA

2

I have a program with 2 classes. The player class that contains only the name attribute:

public class player {
String name;
}

And I have the Main class that has the function below and the same call 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 I want to put their names or get their names. What call should I make on 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 their names. So I had to manipulate the data from that vector

    
asked by anonymous 08.06.2018 / 06:43

1 answer

4

You have a scope problem with the vetor array. Since it was created within for , it only exists while for is running and can only be accessed there as well.

Throwing the line player[] vetor = new player[valor]; out of for solves your problem accessing it.

As for creating and manipulating a Player , you need to create the access methods in the Player class. As it stands today, without a getNome() method, the compiler will complain that this method does not exist:

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

This 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 named Player .

    
08.06.2018 / 13:30