Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA Random Parameter always returns 0

I am practicing techniques learned by writing a small battle simulator. In my hero class I have methods for storing damage. The methods are:

private strike;

public void setStrike(int attack){
    attack = strike;
}

public int retStrike(){
    return strike;
}

In my main method, I have a call for a new Random number.

    int randomNum = new Random().nextInt(10)+1;

    Mike.setStrike(randomNum);

When I call the object Mike and feed the setStrike method in the Hero class's setStrike method, it always returns 0. What am I doing wrong? Thanks!

like image 921
Hermes Trismegistus Avatar asked Mar 30 '26 18:03

Hermes Trismegistus


1 Answers

public void setStrike(int attack){
    attack = strike;
}

This should be: -

public void setStrike(int attack){
    strike = attack;
}

You used your assignment opposite. The first assignment has no effect on the private field strike.

like image 87
Rohit Jain Avatar answered Apr 02 '26 08:04

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!