由于父类没有“answer”变量而子类具有私有的“answer”变量,因此我一直在为我的 Java 项目苦苦挣扎。即使父类中有getAnswer方法,UML图的父类中也没有answer变量。任何建议都非常感谢
这是连接父类及其子类的java文件。子类中唯一的东西是构造函数,而父类只有一个构造函数和 2 个 getter。
import java.util.ArrayList;
import java.util.Random;
/**
*
* @author Admin
*/
public class SimpleQuiz {
private ArrayList<Question> myQuestions;
private int currentQuestion;
public SimpleQuiz()
{
myQuestions =new ArrayList<Question>();
myQuestions.add(new ShortAnswerQuestion("1. What is the color of apple?","Red"));
myQuestions.add(new ShortAnswerQuestion("2. What is my favorite food?","Bacon"));
myQuestions.add(new FillinBlankQuestion("3. I only have to _____ my head above water one more week","keep"));
myQuestions.add(new FillinBlankQuestion("4. eight times _____ is equal to fourty","five"));
myQuestions.add(new TrueFalseQuestion("5. Every animal has a tail","False"));
myQuestions.add(new TrueFalseQuestion("6. A baby has more bones than an average adult","True"));
myQuestions = shuffleList (myQuestions);
currentQuestion=0;
}
public String getCurrentQuestion()
{
return myQuestions.get(currentQuestion).getQuestion();
}
public String getCurrentAnswer()
{
return myQuestions.get(currentQuestion).getAnswer();
}
public boolean checkCurrentAnswer(String answer)
{
return myQuestions.get(currentQuestion).checkAnswer(answer);
}
//Returns true if this quiz has another question
public boolean hasNext()
{
return currentQuestion < myQuestions.size() - 1;
}
public void next() throws Exception
{
if(currentQuestion == myQuestions.size()-1)
{
throw new Exception("There are no more questions.");
}
currentQuestion++;
}
//Shuffle the list
private ArrayList<Question> shuffleList (ArrayList<Question> inputList)
{
ArrayList<Question> randomList = new ArrayList<Question>();
Random r=new Random();
int randomIndex=0;
while(inputList.size() > 0)
{
randomIndex=r.nextInt(inputList.size()); //Choose a random object in the list
randomList.add(inputList.get(randomIndex)); //add it to the new, random list
inputList.remove(randomIndex); //remove to avoid duplicates
}
return randomList; //return the new random list
}
}
答案 0 :(得分:0)
问题对我来说不清楚,你有 UML 并且需要在代码中实现确切的定义?
如果是,我认为只有 3 个选项:
answer
getAnswer()
是抽象的方法getAnswer()
为空,并在子级中覆盖它并返回子级的私有答案答案 1 :(得分:0)
我不确定你从哪里得到了 UML 图,但它可以优化。看问题陈述,问题不应该是一个类,如果不是抽象类,它应该是一个接口,并且不应该有任何实例变量和构造函数。在超类中有一个实例变量“问题”是没有意义的。 Question 超类应该作为一个标记,下面是代码
interface Question{
String getQuestion();
String getAnswer();
boolean checkAnswer(String str);
}
现在实现类需要提供方法的定义。