【发布时间】:2017-07-31 11:02:44
【问题描述】:
我一直对return 关键字的概念及其行为方式感到困惑。我玩了一会儿,发现了一些我无法解释的行为。
在下面的代码中,我有一个简单的calculateScore() 方法,它有一个公式。当第一个方法调用calculateScore() 时,我要求它打印出结果以跟踪我的号码的情况。我用不同的值做了两次。
我的问题是:为什么highscore的值在第一行代码之后就消失了?
此后它只给我返回值0,然后在我第二次调用时再次重复此过程。我不明白。
如果我将highscore 定义为一个值,那么为什么它的值会消失?如果我要返回finalScore,为什么return 保留它?谢谢。
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;
}
}
这是输出:
Result
3300
Your Final Score was 0
0
13600
Your Final Score was 0
0
【问题讨论】:
-
我不太明白这个问题。如果你告诉函数返回 0,那么它总是返回 0。如果你告诉它返回
finalScore的值,那么这就是它返回的值。如果你告诉它返回 0,你为什么期望它返回别的东西? -
你明白
return 0;是做什么的吗? -
您正在返回
0。这就是您分配给highScore的值。您只是将finalScore打印到控制台,而不是将其分配给highScore。你以为你在做什么?
标签: java methods return system.out