如何在方法中稍后识别此变量?

时间:2013-07-02 13:53:41

标签: java variables

大家好我正在写一个数学测验程序作为一个学习练习,我不能得到这个'响应'变量,以便稍后在方法中识别。具体来说,带有* 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;
}

5 个答案:

答案 0 :(得分:3)

response移至外部范围:

int response;

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

局部变量的范围最为有限。这样的变量是   只能从声明它的函数或块访问。   局部变量的范围来自它们声明的行直到   它们的方法或代码块的结束大括号   宣布。

答案 1 :(得分:1)

您需要在response声明之外定义if

int response = -1;

if (number2 > 0) {
    response = /* ... Something ... */
} else {
    response = /* ... Something else ... */
}

答案 2 :(得分:1)

只需在 if声明之前声明

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

或者,找出两个块之间的少量差异,并使用条件运算符改变它:

String separator = number2 > 0 ? "+" : " ";
int response = readInt("What is " + number1 + separator + number2 + "?");

答案 3 :(得分: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");
        }
}

答案 4 :(得分: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 + "?");
}