【发布时间】:2014-05-24 16:35:03
【问题描述】:
我创建了一个数学游戏,它会问十个随机问题并在最后给你打分。我创建了一个名为 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。
【问题讨论】:
-
分数 = + 10;这甚至可以编译吗?
-
它可以编译,但不能满足他的需要。这只是使数字为正并将其分配给变量,但这基本上是没有意义的,因为数字总是为正的。只需说出
score += 10即可修复它。你应该知道这和score = score + 10是一样的,只是一个提高可读性的语法糖。 -
谢谢山猫!我修复了语法。在显示分数的最后一行,Java 说它找不到变量 score。在第 31 行,当 score 被初始化时,它说它从未被使用过。我感觉我可能没有正确使用该变量。
-
编辑了我的答案。这是一个简单的范围问题
-
问题是最后,它不会打印最终分数,因为它说变量没有被使用。如果这是我的 IDE 的问题,我该如何解决?