The correct way would be to create a getter method, to be able to access the live value, from within the Player class.
Follow an example:
Java player.
public class Player {
private boolean vivo;
public Player() {
vivo = true;
}
public void spawn(){
System.out.println("Jogador spawnado");
int vida = 3;
int dano = 1;
int defesa = 1;
}
public boolean getVivo() {
return vivo;
}
}
Then in your class main.java
, just call the method getVivo()
:
while(player.getVivo())//variável que eu quero chamar
{
System.out.println("It just works");
}
Notice that in my solution we made the following steps:
- put the live variable as an instance variable of the Player class.
- We added a constructor method only to start the value of the live variable. (we could create (more than one constructor for example to have one that accepts parameters, to instill our class in a more adaptable way)
- We added a
getter
for the value of the live variable.
- In our main method we use the method
getVivo()
Note that from this we are breaking some principles of object orientation programming using our class in this way, one of them is encapsulation.
If we do not want to break the encapsulation we must have a getter and a Setter for each attribute of our class. A more object-oriented version of our class would be:
Java player.
public class Player {
private boolean vivo;
private int vida;
private int dano;
private int defesa;
public Player() {
//construtor padrão
}
public Player(boolean vivo, int vida, int dano, int defesa) {
this.vivo = vivo;
this.vida = vida;
this.dano = dano;
this.defesa = defesa;
System.out.println("Jogador spawnado");
}
public boolean getVivo() {
return vivo;
}
public int getVida() {
return vida;
}
public int getDano() {
return dano;
}
public int getDefesa() {
return defesa;
}
public void setVivo(boolean vivo){
this.vivo = vivo;
}
public void setVida(int vida) {
this.vida = vida;
}
public void setDano(int dano) {
this.dano = dano;
}
public void setDefesa(int defesa) {
this.defesa = defesa;
}
}
Then in his main.java
simply call the player class constructor with the values to instantiate its class.
Main java.
public class Main {
public static void main(String[] args) {
System.out.println("Bem vindo ao jogo!");
System.out.println("Pressione qualquer tecla para começar");
Scanner in = new Scanner(System.in);
String start = in.nextLine();
//aqui usamos os valores que estavam dentro do método spawn()
Player player = new Player(true, 3, 1, 1);
//player.spawn(); -->não é mais necessário pois estamos utilizando o construtor
while(player.getVivo())//variável que eu quero chamar
{
System.out.println("It just works");
}
}
put the Spawn method as Static
– srluccasonline
I put it, only it keeps giving the same problem :/
– Tired Programmer
And another thing I forgot to mention, put the variables OUT of the method (i.e., in the scope of the class), when you want to access the variables within the method, use THIS or through Getter/Setter
– srluccasonline