变量我正在学习Java,下面的程序只接受0的答案
我有下面的代码来询问一个乘法问题,并询问用户答案,然后检查答案是否正确
我可以让它工作到检查答案的程度。它只接受0,这是因为出于某种原因,我将答案初始化为0
如果我在代码中将其更改为num1*num2,它将不会接受它。我在寻找帮助或资源来帮助我找到答案,我不只是想有人给我答案。提前谢谢
//Multiply.java -- prints multiplication questions for user to answer
import java.util.Random; // import Random
import java.util.Scanner; // import Scanner
public class Test
{
public static void main(String[] args)
{
@SuppressWarnings("resource")
Scanner input = new Scanner( System.in );
int guess; // the user's guess to the question
createQuestion(); // display the first question to the user
System.out.println( "Enter your answer (-1 to exit):" ); // asks the question
guess = input.nextInt(); // accepts the users answer
while ( guess != -1 ) // if guess is not -1
{ // start while
checkResponse( guess ); // calls checkResponse to check guess
System.out.println( "Enter your answer (-1 to exit):" ); // prompts user for answer
guess = input.nextInt(); // the users answer that is entered
} // end while
} // end main
private static void createQuestion()
{ // start createQuestion
Random randomNumbers = new Random();
// get two random numbers between 0 and 9
int num1 = randomNumbers.nextInt( 10 );
int num2 = randomNumbers.nextInt( 10 );
@SuppressWarnings("unused")
int answer = (num1 * num2); // answer to the question
System.out.printf( "How much is %d times %d?\n", // prompts for the answer
num1, num2 );
} // end createQuestion
private static void checkResponse(int guess)
{ // start checkResponse
int answer = 0; /* this is where I have the problem if I change 0
* to (num1 * num2) it can't resolve to a variable. I am trying to bring
* down the answer variable from createQuestion */
if ( guess != answer ) // if the users answer is not correct
System.out.println( "No. Please try again." );
else
{ // start else
System.out.println( "Very Good!" ); // if the users answer is correct
createQuestion();
} // end else
} // end checkResponse
} // end class
# 1 楼答案
在方法checkResponse之外声明“answer”,并将其作为测试类的成员。然后,从createQuestion方法中指定它的值
# 2 楼答案
将
guess
和answer
声明为Test
的属性这样,你就可以在
createQuestion()
和^checkResponse()
两个功能都可以访问正确(和最新)值
# 3 楼答案
您试图在其方法之外使用变量。您应该在方法之外声明变量