所以我有一个作业,我应该用随机数生成一个带五个问题的数学测验,我应该在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 + "%");
}
}
答案 0 :(得分:3)
在if (op...
构造中,只有下一个语句(在本例中为分号,下一行),即println
语句受条件影响,而不是以下行{ {1}}等等。它们是无条件执行的。根据源代码的原始缩进,这不是原始意图。
attempt = scan.nextInt();
如果您希望所有行都受到这些条件的影响,请在 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
这是大多数编码标准强制要求的原因之一。
答案 1 :(得分:1)
你在for的末尾写total=5;
,取消它。并且你在for之前和之后都有{和}}。