I'm learning Java and searched this error, which is very common. But I cannot find the solution. I'm trying to re-use the result of finalScore
, but no matter how I declare it or where I place it, IntelliJ does not recognize it. I know I'm missing something fundamentally obvious here. How can I declare the integers so that they can be re-used in different methods? Anywhere outside of the gameOver
method is a problem. I also tried public static int finalScore
but that also threw error. And calculateScore.finalScore
but still error.
package com.test;
public class Main {
public static void main(String[] args) {
// write your code here
calculateScore(true, 5, 5, 200, "sam");
calculateScore(true, 5, 8, 200, "bob");
}
public static void displayHighScore(){
if (finalScore > 100); //problem line of code
System.out.println("helloworld");
}
public static int calculateScore(boolean gameOver, int score, int levelCompleted, int bonus, String name) {
if (gameOver) {
int finalScore = score + (levelCompleted * bonus);
finalScore += 2000;
System.out.println("your final score was " + finalScore);
return finalScore;
if ((finalScore > 100) || (finalScore < 200));
System.out.println( name "is in position 4");
}
return -1; //if the above isn't required/doesn't run, this statement is: else return -1
//or we can just type is as } else { return -1;
}
}
There are lots of problems in your code here. But for what you mentioned as the issue, you need to declare finalScore as global static
variable as below
...
static int finalScore;
public static void main(String[] args) {
// write your code here
calculateScore(true, 5, 5, 200, "sam");
calculateScore(true, 5, 8, 200, "bob");
}
...
Also, you need to put the return finalScore
statement at the end of the if(gameOver)
block as below or you will get not reachable error for line if ((finalScore > 100) || (finalScore < 200));
if (gameOver) {
finalScore = score + (levelCompleted * bonus);
finalScore += 2000;
System.out.println("your final score was " + finalScore);
if ((finalScore > 100) || (finalScore < 200));
System.out.println( name +"is in position 4");
return finalScore;
}