I am building a small quiz application, and I am storing each answer to each question in a database table (using JPA).
I wonder if there is a way to fetch the getters dynamically through a for loop for example (as is possible with javascript), rather than to have to write out each get method.
The code I have (where "answer" is a class with 9 different integers for each answer).
public void parseUserScore(UserAnswers answer) {
Integer[] answers = new Integer[] {
answer.getQ1(),
answer.getQ2(),
answer.getQ3(),
answer.getQ4(),
answer.getQ5(),
answer.getQ6(),
answer.getQ7(),
answer.getQ8(),
answer.getQ9()
};
double totalscore = 0;
Integer answeredQuestions = 0;
for (int i = 0; i < answers.length; i++) {
if (answers[i] > 0) {
answeredQuestions++;
}
totalscore += answers[i];
}
}
My question is if it is possible to fetch these answers through a foor loop like so:
public void parseUserScore(UserAnswers answer) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i < 10; i++) {
String methodname = "getQ" + i.toString();
list.add(i, answer.methodname)
}
}
This would be preferable since I would like to use the index of each question to separate them based on their respective categories.
From what you provided in your question I think you should use three entities: User
, Question
and Answer
. A user can ask multiple question and submit multiple answers to questions. An answer belongs always to one question. JPA has some annotations to model these rules:
@Entity
class User {
@OneToMany(mappedBy = "user")
Set<Question> questions;
@OneToMany(mappedBy = "user")
Set<Answer> answers;
// Getters & setters
}
@Entity
class Question {
@ManyToOne
@JoinColumn(name = "user_id")
User user;
@OneToMany(mappedBy = "question")
Set<Answer> answers;
// Getters & setters
}
@Entity
class Answer {
@ManyToOne
@JoinColumn(name = "user_id")
User user;
@ManyToOne
@JoinColumn(name = "question_id")
Question question;
int score;
// Getters & setters
}
Afterwards you can simply iterate over the answers of a particular user and calculate the total score:
final int totalScore = user.getAnswers().stream().mapToInt(Answer::getScore).sum();
Please note that this is only a basic example. You should also make considerations about cascading updates and fetch types of the relations.
Regarding you question about the for loop: Java provides a feature called 'Reflection'. It is a mechanism for meta-programming and could be used to achieve what you described. However, this is a bad idea because it has some drawbacks and it makes no sense in your case as a user should be able to answer more than 10 questions. In fact you can not know how many answers a user will submit.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.