我正在学习Java并搜索了这个错误,这很常见。但我找不到解决方案。我试图重新使用finalScore
的结果,但无论我如何声明它或放置它,IntelliJ都不会识别它。我知道我在这里遗漏了一些根本明显的东西。如何声明整数以便可以在不同的方法中重复使用它们? gameOver
方法之外的任何地方都是个问题。我也试过了public static int finalScore
,但也犯了错误。并且calculateScore.finalScore
但仍然是错误。
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;
}
}
答案 0 :(得分:0)
这里的代码存在很多问题。但是对于您提到的问题,您需要将finalScore声明为全局static
变量,如下所示
...
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");
}
...
此外,您需要将return finalScore
语句放在if(gameOver)
块的末尾,如下所示,否则您将无法获得第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;
}