我创建了一个数学游戏,它会随机提出十个问题并在最后给你打分。我创建了一个名为 score 的整数变量并将其初始化为 0。在 if 语句中,如果你回答正确,你将获得 10 分。我想既然我在 for 循环中有 score + 10 那么我不应该为评分系统使用增量。如果有人能指出正确的方向,说明为什么 Java 告诉我没有使用 score 变量,我将不胜感激。来自德克萨斯的欢呼!
package pkgnew;
import java.util.Scanner;
import java.util.Random;
public class New {
public static void main(String args[]) {
//Game 10x loop
for(int i = 0; i < 10; i++)
{
//Declare and construct variables
Random randomnum = new Random();
int fnum, snum;
int mathnumber = randomnum.nextInt(20);
int newnumber = randomnum.nextInt(20);
//Declare and construct variables of math problem
fnum = mathnumber;
snum = newnumber;
//Declare random operator variable
String[] operators = {"+" , "-", "*", "/" };
int randomIndex = randomnum.nextInt(3);
String symbol = operators[randomIndex];
//Initialize answer and score
int answer = 0;
int score = 0;
//Switch statement for random operator and question display
switch (symbol) {
case "+":
System.out.println(fnum + "+" + snum);
answer = fnum+snum;
break;
case "-":
System.out.println(fnum + "-" + snum);
answer = fnum-snum;
break;
case "*":
System.out.println(fnum + "*" + snum);
answer = fnum*snum;
break;
case "/":
System.out.println(fnum + "/" + snum);
answer= fnum/snum;
break;
}
//User input
Scanner serena = new Scanner(System.in);
int userAnswer = serena.nextInt();
//If user input = answer display "correct"
if (userAnswer == answer) {
System.out.println("Correct!");
score = + 10;
//If user input does not = answer display "wrong" and correct answer
} else {
System.out.print("Wrong! The correct answer is: " );
System.out.println(answer);
}
}
System.out.println("Game Over!");
System.out.println("Your score is:");
System.out.println(score);
}
}
我使用 Java 8 和 NetBeans 8.0。
最佳答案
您遇到问题是因为您在 for 循环内初始化变量,然后尝试在外部使用它,这是不可能的,因为这就是语言的制作方式。这称为 scope
。而且您应该知道,变量仅在已声明的范围(括号中)内有效。就像您的情况一样,它仅在 for 循环中可用,然后由垃圾收集器收集。这没什么大不了的,只需在执行 for 循环之前定义 score 变量即可。
int score;
for(int i...)
{
// ...
}
// now you can use score here:
还有一件事:您根本没有增加 score 变量。你只是在说 score = +10
。这只是让正数 10 成为正数,将其分配给变量,无论变量分数有什么数据,它都不再有它,这不是你想要做的。我认为您想要使用的正确方法是像这样使用 += 运算符:score += 10;
。 += 是一种语法糖,用于提高可读性,其作用与 score = score + 10;
完全相同。
关于java - 分数变量未在数学游戏程序中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23847351/