在这里,我试图为Question和ChoiceQuestion类提供一些toString方法。应该打印问题文本(针对两个类),并打印带有ChoiceQuestion选项的选项号。知道我在ChoiceQuestion类中缺少什么来完成这项工作吗?任何帮助,将不胜感激!
What was the original name of the Java language?
1: *7
2: Duke
3: Oak
4: Gosling
/**
A question with multiple choices.
*/
class ChoiceQuestion extends Question
{
private ArrayList<String> choices;
/**
Constructs a choice question with no choices.
*/
public ChoiceQuestion()
{
choices = new ArrayList<String>();
}
/**
Adds an answer choice to this question.
@param choice the choice to add
@param correct true if this is the correct choice, false otherwise
*/
public void addChoice(String choice, boolean correct)
{
choices.add(choice);
if (correct)
{
// Convert choices.size() to string
String choiceString = "" + choices.size();
setAnswer(choiceString);
}
}
public String toString()
{
return choices.toString() + super.toString() ;
}
}
class Main {
public static void main(String[] args) {
Question question = new Question();
question.setText("Who was the inventor of Java?");
question.setAnswer("James Gosling");
boolean resultQuestion = question.checkAnswer("Andrew Gosling");
String toStringOutputQuestion = question.toString();
ChoiceQuestion choiceQuestion = new ChoiceQuestion();
choiceQuestion.setText("What was the original name of the Java language?");
choiceQuestion.addChoice("*7", false);
choiceQuestion.addChoice("Duke", false);
choiceQuestion.addChoice("Oak", true);
choiceQuestion.addChoice("Gosling", false);
boolean resultChoiceQuestion = choiceQuestion.checkAnswer("3");
String toStringOutputChoiceQuestion = choiceQuestion.toString();
}
}
/**
A question with a text and an answer.
*/
class Question
{
private String text;
private String answer;
/**
Constructs a question with empty question and answer.
*/
public Question()
{
text = "";
answer = "";
}
/**
Sets the question text.
@param questionText the text of this question
*/
public void setText(String questionText)
{
text = questionText;
}
/**
Sets the answer for this question.
@param correctResponse the answer
*/
public void setAnswer(String correctResponse)
{
answer = correctResponse;
}
/**
Checks a given response for correctness.
@param response the response to check
@return true if the response was correct, false otherwise
*/
public boolean checkAnswer(String response)
{
return response.equals(answer);
}
public String toString()
{
return text + answer;
}
}
嗯,准确地定义您遇到的问题很有帮助。
这里是我发现的东西的快速浏览...
1)您需要在Arraylist的顶部使用import语句:“ import java.util.ArrayList;”
2)您至少需要一个公共课:“公共课Main {”
3)您的程序未在屏幕上输出任何内容。添加一些System.out.println行。