2

嗨,伙计们,我正在编写一个数学测验程序作为学习练习,我无法让这个“响应”变量稍后在该方法中被识别。具体来说,两边带有 *s 的 'response' 变量不会链接到前面声明的响应变量。我是编程新手,所以很确定我犯了一个基本错误,但我无法解决,如果有人能帮助我,我将不胜感激。谢谢!

import acm.util.*;
import acm.program.*;


public class MathsQuiz extends ConsoleProgram{

    public void run(){
        println("This program gives atudents a series of maths questions");
        askQuestions();
    }

    private void askQuestions(){
        for (int i = 0; i < NUMBER_OF_QS; i++){
            askQ();
        }
    }

    private void askQ(){
        int answer = rgen.nextInt(0,20);
        int number1 = rgen.nextInt(0,20);
        int number2 = answer - number1;

        if (number2 > 0){
            int response = readInt("What is " + number1 + "+" + number2 + "?");

        }else {
            int response = readInt("What is " + number1 + " " + number2 + "?");
        }

                if (**response** == answer){
                    println("Correct!");
                }else{
                    println("Incorrect");
                }
        }


    private RandomGenerator rgen = RandomGenerator.getInstance(); 

    int NUMBER_OF_QS = 5;
    int RES = 0;
}
4

5 回答 5

3

移动response到外部范围:

int response;

if (number2 > 0) {
    response = readInt("What is " + number1 + "+" + number2 + "?");
} else {
    response = readInt("What is " + number1 + " " + number2 + "?");
}

局部变量的范围最有限。这样的变量只能从声明它的函数或块中访问。局部变量的范围是从声明它们的行到声明它们的方法或代码块的右花括号。

于 2013-07-02T13:55:31.970 回答
1

您需要在语句response之外定义:if

int response = -1;

if (number2 > 0) {
    response = /* ... Something ... */
} else {
    response = /* ... Something else ... */
}
于 2013-07-02T13:55:27.877 回答
1

只需在声明之前声明if它:

int response;
if (number2 > 0) {
    response = ...
} else {
    response = ...
}

或者,发现两个块之间的少量差异,并使用条件运算符进行更改:

String separator = number2 > 0 ? "+" : " ";
int response = readInt("What is " + number1 + separator + number2 + "?");
于 2013-07-02T13:55:42.780 回答
1

这是因为您正在 if 语句中创建变量响应。试试这个

private void askQ(){
int answer = rgen.nextInt(0,20);
int number1 = rgen.nextInt(0,20);
int number2 = answer - number1;
int response; //to create the variable in the right scope


if (number2 > 0){
    response = readInt("What is " + number1 + "+" + number2 + "?");

}else {
    response = readInt("What is " + number1 + " " + number2 + "?");
}

        if (**response** == answer){
            println("Correct!");
        }else{
            println("Incorrect");
        }
}
于 2013-07-02T13:56:30.080 回答
1

response是一个局部变量,它的可访问性仅限于声明它的块内部。因此,response只能在if else块内访问。如果你尝试在response作用域之外使用,你会得到一个编译时错误,直到你不重新声明它。

所以,如果你想在if else块外使用响应,你必须在块外声明它,如下所示:

int response;
if (number2 > 0){
     response = readInt("What is " + number1 + "+" + number2 + "?");
}else {
     response = readInt("What is " + number1 + " " + number2 + "?");
}
于 2013-07-02T14:20:13.467 回答