【发布时间】:2015-05-12 14:45:36
【问题描述】:
所以我有一个作业,我应该在其中生成一个包含随机数的五个问题的数学测验,并且我应该在 for 循环中为具有某些数学属性的数学运算符分配 0-2。我在这里束手无策;我不明白为什么它不再循环重复。
import java.util.Scanner;
import java.util.Random;
public class MathQuizS2 {
public static void main(String args[]){
int first, second, sum;
int attempt, diff, mult;
int op;
int total;
final int correctMax = 5;
int correct = 0;
int incorrect = 0;
double grade;
Scanner scan = new Scanner(System.in);
Random generator = new Random();
op = generator.nextInt(3);
first = generator.nextInt(11);
second = generator.nextInt(11);
sum = first + second;
diff = first - second;
mult = first * second;
{
for (total=0; total<=correctMax; total++)
{
if (op == 0)
System.out.println(" What is the sum of " + first + " + " + second + " ? ");
attempt = scan.nextInt();
if (sum == attempt) {
System.out.println("You are correct");
correct++;
}
else {
System.out.println("Incorrect the sum is " + sum);
incorrect++;
}
if (op == 1)
System.out.println(" What is the difference between " + first + "-" + second + " ? ");
attempt = scan.nextInt();
if (diff == attempt) {
System.out.println("You are correct");
correct++;
}
else {
System.out.println("Incorrect the difference is " + diff);
incorrect++;
}
if (op == 2)
System.out.println(" What is the product of " + first + " * " + second + " ? ");
attempt = scan.nextInt();
if (mult == attempt) {
System.out.println("You are correct");
correct++;
}
else {
System.out.println("Incorrect the product is " + mult);
incorrect++;
}
total = 5;
}
}
grade = (double) correct/5 * 100;
System.out.println(" You got " + correct + " correct and " + incorrect + " incorrect of 5 questions, your grade is " + grade + "%");
}
}
【问题讨论】:
-
在for循环的第一次迭代结束时,您分配total = 5。在下一次迭代开始时total增加到6,大于correctMax。因此,您退出了 for 循环。你确定你的逻辑是正确的?
-
我不确定这里有什么问题。我拿出total=5;因为也许它在错误的位置,但现在它只评估一个 if 。我需要解决什么问题?
-
好的,当我将 { 放在第一个嵌套 if 语句之后并在 else 之后关闭它时,它只会在循环中评估该问题 5 次。如果我把它放在第一个 if 语句之后,那么它说我的变量没有初始化。我希望它评估所有 3 个问题,最后 2 个是随机的。另外,if 语句每次都有可能生成新的数字吗?它使用第一次生成的相同数字。