我在Java中进行代数测验,我想检查用户的答案是否与代数方程的答案相同。这就是我已经得到的,检查是在底部。第一个if语句是检查第二个数字是正数还是负数并计算它。第二个if语句试图查看用户答案是否与问题答案相同。问题是Int的答案不能转移到另一个if语句。有没有办法解决这个问题?它使用这样的代数方程:1x + 2 = 5.
int numRight = 0;
Scanner input = new Scanner(System.in);
System.out.println("Welcome to your algebra test!");
System.out.println("What is your name?");
String name = input.nextLine();
System.out.println("Ok, " + name + ", how many questions do you want on your test?");
int numQuestions = input.nextInt();
for(int x = 0; x <= numQuestions; x++){
int coefficient = 7;
int num1 = 3;
int num2 = 23;
while((num2 - num1) % coefficient != 0){
coefficient = (int) (Math.random()*8)+2;
num1 = (int) (Math.random()*19)-9;
num2 = (int) (Math.random()*90)+10;
}
if(num1 > 0){
int part1pos = num2 - num1;
int answer = (coefficient / part1pos);
} else if(num1 < 0){
int part1neg = num1 + num2;
int answer = (coefficient / part1neg);
}
System.out.println(coefficient + "x + " + num1 + " = " + num2);
int userAnswer = input.nextInt();
if(userAnswer == answer){
System.out.println("The Answer is correct!");
numRight++;
} else{
System.out.println("The answer is wrong!");
}
}
答案 0 :(得分:1)
问题是你的答案整数是在与检查答案正确性的布尔语句不同的范围内声明的。您应该在该布尔语句之外声明并初始化您的答案为0,在您声明系数, num1 和 num2 的位置附近。