-5

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
Jameson
  • 6,400
  • 6
  • 32
  • 53
  • 3
    I don't really understand the question. If you tell the function to return 0, then it always return 0. If you tell it to return the value of `finalScore`, then that's what it returns. Why would you expect it to return something else if you tell it to return 0? – JJJ Mar 10 '17 at 07:32
  • Do you understand what `return 0;` does? – Stephen C Mar 10 '17 at 07:33
  • You're returning `0`. That's the value you're assigning to `highScore`. You're only printing `finalScore` to the console, and not assigning it to `highScore`. What did you think you were doing? – Krease Mar 10 '17 at 07:38

5 Answers5

1

Well, you need to change the way you think this works.

Variables that are defined inside a method only retain that value inside that method.

The meaning of return is not "keep" or "store". It means "pass this value to the method that called this method, and then return to the place where it was called".

So when you have

void methodA() {
   int a = methodB();
   System.out.println(a);
}

int methodB() {
   int b = 5;
   return 0;
}

Then when methodA calls methodB, execution goes into the first line of methodB, which gives a number to a variable (but never uses it), and then the return tells it that the value to return is 0, and then it leaves methodB and returns to the call in methodA, and hands that 0 to the variable a. It is at this point (the assignment) that the value is "kept". The chain of execution you had here is:

  • Put 5 in the variable b in methodB
  • Designate 0 as the value to return from methodB
  • Discard the variable b as we are leaving methodB
  • Return to methodA
  • Assign the designated value (0) to variable a in methodA
  • Print the value of variable a.
RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
0

First observation: in calculateScore() you use a variable named finalScore while in your main()-method you use highScore - so even if your reasoning was correct the two variables' names would not match.

But even if the names were the same you would get the same results since variables in java are not globals but have a scope. As a rule of thumb: when a variable is declared in a block enclosed in {} it is only known in this block and disapears once execution leaves the block. That is why we have the return-statement: when your method needs to provide a result to the calling method it returns it and the calling method can then assign it to its own variable.

piet.t
  • 11,718
  • 21
  • 43
  • 52
0

I like to think of return as saying the value that the method represents.

You see how calculateScore here can be used like a value of a variable?

int highScore = calculateScore(true, 800, 5, 100);

You can't do this with other methods like System.out.println:

int highScore = System.out.println(); // does not compile

That is because calculateScore's signature says that it returns an int i.e. it can "represent" an integer value. But what value does it represent exactly? That all depends on the return statement. Here, your return statement says:

return 0;

That means the method always represents the value of 0. In other words,

int highScore = calculateScore(true, 800, 5, 100);

is the same as

int highScore = 0;

That's why the second line of output shows you 0.

So what value should the method represent? The value of the finalScore variable, of course! But apparently you only calculate the highscore if gameOver. You should add a new return statement in side the if statement:

if (gameOver) {
    // your original formula and stuff
    return finalScore;
}

Remember to keep the return 0 statement because what if gameOver is false? What value does the method represent? It can't represent nothing because the method signature says that it represents an int. So I think here the most appropriate thing to do is to return 0.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0
   public static int calculateScore(boolean gameOver,
        int score, int levelCompleted, int bonus) {

    int finalScore = 0; 

    if (gameOver) {

        finalScore  =  (score + (levelCompleted * bonus));
        finalScore +=2000;

    }

    return finalScore ;

}

In your calculateScore method, you always return 0. If you want to get calculated amount as a score. you have to return it from your method. And you have to initialize the finalScore variable in the beginning of method.

Kaushali de Silva
  • 241
  • 1
  • 3
  • 9
-1

What return does is pass back a value so that it can be used.

You're telling your function to print finalScore but in the end the value you're only passing the number 0; the variable receives a value of 0, completely disregarding what it calculated and showed you on the console. That's why you always get a 0 when you print with System.out.println(highScore);.

Just swap out 0 for finalScore to get it working.

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 finalScore;
}
}
luni3359
  • 25
  • 6