Reputation: 23
I have two methods that use the same variable pikaHP
. The first method works fine in subtracting and printing out the value for pikaHP
, but when I go to the next method right after that, the value has been reset to its original value.
Here is what some of the code looks like:
int pikaHP = 30;
static void fight(int pikaHP, /*(insert other variables here)*/)
{
pikaHP = pikaHP - 5; //outputs 25 fine on the next line
System.out.println("Pikachu's hp is " + pikaHP);
}
static void currentHP(int pikaHP /*(inster other variables here)*/)
{
//This time pikaHP is printed as 30
System.out.println("pikachu's hp is " + pikaHP);
}
I'm guessing this is happening because pikaHP
is set to 30 in the main
method and both methods just grab that amount of 30.
How do I save pikaHP
as 25 (or whatever value I want) in the fight()
method and then carry that 25 over to currentHP()
method so it outputs "pikachu's hp is 25" instead of 30?
Upvotes: 1
Views: 176
Reputation: 394126
A method can only change the value of a variable passed to it (such as pikaHP
) locally, since Java is a pass by value language. It you want the change to survive the method call, make the variable static instead of passing it to these static methods.
An alternative (if this variable is declared locally in the main method and you want to keep it this way) is that each method that gets this variable as an argument and wishes to change its value would return the modified value of that variable, and your main method would assign the new value to the variable.
Upvotes: 1