gpt4 book ai didi

java - 如何让这个变量稍后在方法中被识别?

转载 作者:行者123 更新时间:2023-12-02 07:35:05 25 4
gpt4 key购买 nike

大家好,我正在编写一个数学测验程序作为学习练习,我无法在方法的后面识别这个“响应”变量。特别是带有 *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;
}

最佳答案

response 移动到外部范围:

int response;

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

Local variables have the most limited scope. Such a variable is accessible only from the function or block in which it is declared. The local variable's scope is from the line they are declared on until the closing curly brace of the method or code block within which they are declared.

关于java - 如何让这个变量稍后在方法中被识别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17427462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com