Luis Carcamo Luis Carcamo - 11 months ago 45
Java Question

whats is wrong in this basic method Java?

i'm newbe in this programming language (in almost too), i just wanna use a "if and else" with getter and setter methods, i'm doing a basic RPG for learning purpose.
I've a character x, and all i wanna do is; if the life of this character is lower than 0 revive this character,else just increase his life. This is my

public Skill bless(Character x) {
if (0>= x.getCurrentHp()) {
x.getCurrentHp() == x.getHp() * 3/4;
else if (x.getCurrentHp() > 0) {
x.getCurrentHp() =+ x.getHp() * 1/2;
return x;

Answer Source

Well, the issue is in these lines:

x.getCurrentHp() == x.getHp() * 3/4;
x.getCurrentHp() =+ x.getHp() * 1/2;

You have to use methods like:

x.setCurrentHp(x.getHp() * 3/4);
x.setCurrentHp(x.getHp() * 1/2);

Under the hood methods setCurrentHp / getCurrentHp should be like the following:

public class Character {
    private int currentHp;
    // ... other methods and fields

    public void setCurrentHp(int hp){ currentHp = hp; }

    public int getCurrentHp(){ return hp; }

Because when you call x.getCurrentHp() it simply returns the value. And then you are just assigning x.getHp() * 1/2 to that value.

As a tutorial, you can refer to official examples of getter/setter methods.