【发布时间】:2020-11-19 16:05:44
【问题描述】:
问题 考虑在一个测试中有 4 个测试问题。 1 页由 1 个问题组成,为多项选择。您可以使用特定命令在问题之间前后移动。每一页都应表示为一个类,最后一页是您在这些问题中选择的内容的摘要。 编写一个允许您使用 OOP 执行此操作的程序。
命令 - 用户可以在程序中使用
start() - To start the test and the first page of the test should be given once this command run.
next_page() - To move to the next page
back_page() - To move back a page
select(int i) - Select an answer on the current page
我遇到了上述问题,我需要编写一个按预期工作的程序。这是我到目前为止所拥有的。我可以随意设计程序,没有任何限制。如果我下面的设计完全错误,请随时告诉我应该如何解决这个问题。
这是我的 Question 类的样子:
class Question1
int answer;
void display(){
print("This is Question1")
print("1. Answer")
print("2. Answer")
print("3. Answer")
print("You have selected:" + answer);
}
void select(int i){
this.answer = i;
}
在其他问题类中。它看起来相似但不同的问题和选择。
在摘要类中,它将打印出我选择的内容
class Summary() {
void display(){
print("Summary")
print("In question 1, you've selected: " + Question1.answer);
print("In question 2, you've selected: " + Question2.answer)
print("In question 3, you've selected: " + Question3.answer)
print("In question 4, you've selected: " + Question4.answerr);
}
}
我有一个应用程序类。这就像这个程序的大脑。它存储了打印正确的 display() 方法类所需的所有信息。它跟踪我现在在哪个页面上。此外,我可以转到下一页、后退一页或在当前页面上选择答案。另外,我有一个抽象的 Page 类,其中每个问题都继承自 Page 类。
//How exactly does the page cluster work?
+--------+---- Page -+---------+-----------+(This is an abstract class)
| | | | |
Question1 Question2 Question3 Question4 Summary (This the 5 pages, that inherited from Page class with)
class Application
int current_p; // Current position of the question.
Page p[] = new Page[5];
public Application(){//Constructor
p[0] = new Quesion1;
p[1] = new Quesion2;
p[2] = new Quesion3;
p[3] = new Quesion4;
p[4] = new Summary;
current_p = 1;
}
public start(){
p[current_p].display();
}
public next(){
current_p++;
p[current_p].display();
}
public back(){
current_pn--;
p[current_p].display();
}
public select(int i){
p[cuurent_p].select(i);// Go back to my Question class to see how select work.
p[current_p].display();
}
因为这太长了,它可能会对我正在尝试做的事情感到困惑。这是一个输出示例
Main(){
Application a = new Application();
a.start();
a.select(2);
a.next();
a.select(1);
a.next();
a.next();
a.next();
}
在命令行中应该输出如下内容:
This is Question1
1. Answer
2. Answer
3. Answer
You have selected: 0
This is Question1
1. Answer
2. Answer
3. Answer
You have selected: 2
This is Question2
1. Answer
2. Answer
3. Answer
You have selected: 0
This is Question2
1. Answer
2. Answer
3. Answer
You have selected: 1
This is Question3
1. Answer
2. Answer
3. Answer
You have selected: 0
This is Question4
1. Answer
2. Answer
3. Answer
You have selected: 0
Summary
In question 1, you've selected: 2
In question 2, you've selected: 1
In question 3, you've selected: 0
In question 4, you've selected: 0
所以我现在的问题是我找不到从每个问题中获取答案并从 Summary 类中显示它的方法。我应该如何更改我的设计,或者如果我的设计仍然有效,我应该怎么做?
【问题讨论】:
-
您可以将问题存储在列表或数组中,然后将位置存储为整数。如果用户使用
.next()命令,则增加位置并在该位置打印出数组中的项目。
标签: java inheritance polymorphism