I've been stumped over the concept of the return
keyword and how it behaves. I've been playing around a bit and found some behavior I can't explain.
In my code below, I have a simple calculateScore()
method that has a formula. When the first method calls calculateScore()
, I ask it to print out the result to keep track of what's going on with my numbers. I do this twice with different values.
My question is: How come the value of highscore
disappears after the first line of code?
Thereafter it only gives me my return value of 0
, and then repeats this process again on my second call. I don't understand.
If I am defining highscore
as a value, then why does it's value disappear? And why does return
keep it, if I were to return finalScore
instead? Thank you.
public class Main {
public static void main(String[] args) {
int highScore = calculateScore(true, 800, 5, 100);
System.out.println("Your Final Score was " + highScore);
System.out.println(highScore);
highScore = calculateScore(true, 10000, 8, 200);
System.out.println("Your Final Score was " + highScore);
System.out.println(highScore);
}
public static int calculateScore(boolean gameOver,
int score, int levelCompleted, int bonus) {
if (gameOver) {
int finalScore = score + (levelCompleted * bonus);
finalScore +=2000;
System.out.println(finalScore);
}
return 0;
}
}
This is the output:
Result
3300
Your Final Score was 0
0
13600
Your Final Score was 0
0