Doubt about filling arrays and functions within arrays

1
  

insira o código aquiArrayList<Player> players = new ArrayList<Player>(); for(contador=0;contador<x;contador++){ Player p1 = new Player(); p1.setId(contador); p1.setSaldo(valorinteger = Integer.parseInt(parts[2])); players.add(p1); }

1 - I need to create X players in this array, and each 1 will have a different balance. how can I do this since that is not working.

2 - I have array players, and I need to call a function, for example, getsaldo (); of / each of the players that is in the array. How can I do this? Thanks for the help, I have a great job to deliver and I know very little about java.

    
asked by anonymous 07.06.2017 / 05:29

1 answer

0

Your Player object is a class, you are already setting a set method that assigns the value of the balance of the player in each instance that you are creating in for, so you can get the value of each player within the array players, the ArrayList with a for and use the getSaldo () method of each Player, but for this you will have to create this method within the Player class. Example:

ArrayList<Player> players = new ArrayList<Player>();
    int valorfixo = 5;
    for (int contador = 0; contador < valorfixo; contador++) {
        Player p1 = new Player();
        p1.setId(contador);
        int valorRandomico = (int) (Math.random() * 100);
        p1.setSaldo(valorRandomico);
        players.add(p1);
    }

    for (Player player : players) {
        System.out.println(player.getSaldo());
    }

Player class:

public class Player {
private int id;
private int saldo;
public Player(){

}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public int getSaldo() {
    return saldo;
}
public void setSaldo(int saldo) {
    this.saldo = saldo;
}}
    
07.06.2017 / 12:40