![](/img/trans.png)
[英]Java - Is it possible to subclass an array? And more questions about arrays in Java
[英]Sections of Questions As Subclass in Java
我有一类带有不同部分的问题-某些部分根据其他答案显示给用户。 始终会回答第1节。 仅在某些情况下回答第2和3节。
如何最好地将这些问题“分组”,以便我可以轻松地检查给定组中的正确答案总数 (包含true
/ false
),并检查各部分是否回答了所有问题 ?
问题中的数据是从Spring项目中的Web UI返回的。 我认为可能的值为true
, false
或null
。
@Entity
public class LicenseApplication {
// Section 1
private boolean question1;
private boolean question2;
//Section 2
private boolean question3;
private boolean question4;
}
您可以执行以下操作
class Section
{
public List<Question> questions;
//...
}
class Question
{
public boolean isCorrect;
//...
}
public boolean entireSectionCorrect(Section section)
{
for (int i=0; i<section.questions.size(); i++) {
if(!section.questions[i].isCorrect)
return false;
}
return true;
}
@AlanCPSC有很好的建议,因为可以纠正一些问题
class Section
{
private List<Question> questions;
public int getCount()
{
int count=0;
for(Question quest : questions)
{
boolean answer = quest.getAnswer().get(quest.getQuestion());
boolean answered = quest.getAnswered().get(quest.getQuestion());
if(answer == answered)
{
count++;
}
}
return count;
}
...
}
class Question
{
private String question;
private Map<String, Boolean> answer; // correct answer
private Map<String, Boolean> answered; // answered by candidate
...
}
我对OP造成的混乱以及其他答案的过大失望感到有些失望,所以这是我的看法...
免责声明:我离开Java已有一段时间了,我已经用内存对它进行了编码...原谅任何错误(但请指出这些错误,以便我进行修复)。
public class Section {
public boolean[] questions[];
public Section(int questionAmount){
questions = new boolean[questionAmount];
}
public boolean isEveryQuestionAnswered() {
for(boolean question : questions) {
if(!question) //If any question is not answered.
return false;
}
//If reached this point, all questions were answered, so...
return true;
}
public int totalNumberOfTrues() {
int count = 0;
for(boolean question : questions) {
if(question) //If any question is answered.
count++;
}
//If reached this point, all 'true' questions were accounted for, so...
return count;
}
}
public class LicenseApplication {
private Section[] sections = new Section[3];
// Section 1
sections[0] = new Section(2);
sections[0].questions[0] = false;
sections[0].questions[1] = true;
//...
System.out.println("Section 1 complete: "+sections[0].isEveryQuestionAnswered()) //Prints "Section 1 complete: false"
System.out.println("Section 1 total answered: "+sections[0].totalNumberOfTrues()) //Prints "Section 1 total answered: 1"
//Section 2
sections[1] = new Section(3);
sections[1].questions[0] = true;
sections[1].questions[1] = true;
sections[1].questions[2] = true;
//...
System.out.println("Section 2 complete: "+sections[1].isEveryQuestionAnswered()) //Prints "Section 2 complete: true"
System.out.println("Section 2 total answered: "+sections[1].totalNumberOfTrues()) //Prints "Section 2 total answered: 3"
//INSERT [Section 3] here at will...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.