Doubt to create and work with JAVA class array

Asked

Viewed 1,893 times

2

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

public class player {
String name;
}

And I have the Main Class that has the function below and the call of the same in the 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 get 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 their names. So I had to manipulate the data from this vector

  • The class Principal would be the game ? And why doesn’t it have the vector of players ? Better would be up to a ArrayList<Player> to be easy to manage the amount of players you have. vetor[0].getName(); doesn’t work because you have no method getName in class Player.

1 answer

4

You have an array scope problem vetor. How he was created inside the for, it will exist only as long as the for is being executed and can only be accessed there too.

Playing the line player[] vetor = new player[valor]; out of the for solves your access problem to it.

How to create and manipulate a Player, you need to create the access methods in the class Player. The way it is today, without a method getNome(), compiler will claim 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 inside the for to create and name a Player:

Player player = new Player();
player.setName("Joaquim");
vetor[i] = player;

To display the newly created player name, you could add the following line at the end of the for:

System.out.println(vetor[i].getNome());

*Beware of class name using lower case letters only. Although technically valid, it is not good practice in Java. Instead of player, your class should be called Player.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.