【发布时间】:2015-08-09 00:03:06
【问题描述】:
我是编程新手,似乎遇到了变量、类等何时可以引用和不能引用的问题。下面是一个例子,希望你们能解决具体问题,但也能帮助我更广泛地理解它,这样我就不会一次又一次地遇到它。
要尽量避免发布一堆代码,请注意定义了一个 Question 类以及 setText、setAnswer、checkAnswer 和 display 方法都在其他地方定义(全部公开)。
相关代码如下,我有两个问题:
- 为什么
presentQuestion()方法中不能识别变量first? - 最后,为什么我不能先调用方法
checkAnswer(),即为什么我不能直接调用first.checkAnswer(response);?为什么我必须在一个新变量中定义它:boolean outcome = first.checkAnswer(response);?
代码:
/**
* This program shows a simple quiz with two questions.
*/
public class QuestionDemo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Question first = new Question();
first.setText("Who was the inventor of Java?");
first.setAnswer("James Gosling");
Question second = new Question();
second.setText("Who was the founder of Udacity?");
second.setAnswer("Sebastian Thrun");
int score = 0;
score = score + presentQuestion(first, in);
// Present the second question
score = score + presentQuestion(second, in);
System.out.println("Your score: " + score);
}
/**
* Presents a question to the user and obtains a response.
* @param q the question to present
* @param in the scanner from which to read the user input
* @return the score (1 if correct, 0 if incorrect);
*/
public static int presentQuestion(Question q, Scanner in) {
// Display the first question
first.display();
System.out.println("Your answer:");
String response = in.nextLine();
// Check whether the response was correct
// If so, print "true" and return 1
// Otherwise, print "false" and return 0
boolean outcome = first.checkAnswer(response);
System.out.println(outcome);
if (outcome) {
return 1;
}
else {
return 0;
}
}
}
【问题讨论】: