一旦问题得到解答,我问用户10个多项选择问题我希望根据他们的答案显示结果。我想知道是否有更好的方法来计算他们的分数然后只是做了很多if语句?
Int result = 100;
if (answer1 == 10) {
result = result +10;
if (answer2 ==20 ) {
result = result -5;
if (answer3 == 50) {
result = result +20;
}
else if (answer3 == 10)
...
它会继续......
答案 0 :(得分:3)
Map<String, Integer>
,您可以使用Map<Map<String,Boolean>, Integer>
之类的内容,其中整数是最终得分。
这是一种常见的方法:
Map<String, Integer> choice_delta = // new Map
// Define choice delta pairing
choice_delta.put("answer5", -5);
choice_delta.put("answer6", 20);
// etc. etc.
int calculate(String[] answers){
int result = 0;
for (String answer : answers){
int delta = choice_delta.get(answer);
result += delta;
}
return result;
}
答案 1 :(得分:3)
如果您正确建模,则更容易实施。我不确定你的问题背景,但我在这里做了一些假设就是我想出来的。
<强>叙事强>
Quiz
是一组Question
。每个问题都有一个或多个Answer
个,每个答案都带有一定的weight
。您prepare
针对特定场景(Java,c#)的测验并逐一呈现给用户。用户selects
回答所提出的问题,然后向他显示currentScore
和下一个问题。在提出所有问题后,计算出finalScore
。
<强>抽象强>
<强>实施强>
public class Quiz
{
List<Question> questions = new ArrayList<Question>();
List<String> selectedAnswers = new ArrayList<String>();
private int currentScore;
public void prepare()
{
questions.add(new Question("What comes after A?", Arrays.asList(new Answer("B", 10), new Answer("Z", 5))));
questions.add(new Question("What comes after B?", Arrays.asList(new Answer("A", -5), new Answer("C", 10))));
}
public int finalScore()
{
int result = 0;
for (int i = 0; i < questions.size(); i++)
{
result = result + questions.get(i).scoreFor(selectedAnswers.get(i));
}
return result;
}
public void setSelectedAnswerFor(int questionIndex, String selectedAnswer)
{
assert questionIndex < questions.size();
selectedAnswers.add(questionIndex, selectedAnswer);
currentScore = currentScore + questions.get(questionIndex).scoreFor(selectedAnswer);
}
public int currentScore()
{
return currentScore;
}
public static void main(String args[])
{
Quiz quiz = new Quiz();
quiz.prepare();
quiz.setSelectedAnswerFor(0, "B");
System.out.println("Current Score " + quiz.currentScore());
quiz.setSelectedAnswerFor(1, "A");
System.out.println("Current Score " + quiz.currentScore());
System.out.println("Final Score " + quiz.finalScore());
}
}
public class Question
{
private final String text;
private final Map<String, Integer> weightedAnswers;
public Question(String text, List<Answer> possibleAnswers)
{
this.text = text;
this.weightedAnswers = new HashMap<String, Integer>(possibleAnswers.size());
for (Answer ans : possibleAnswers)
{
weightedAnswers.put(ans.text, ans.score);
}
}
public int scoreFor(String selectAnswer)
{
return weightedAnswers.get(selectAnswer);
}
public String getText()
{
return text;
}
}
public class Answer
{
final String text;
final int score;
public Answer(String text, int score)
{
this.text = text;
this.score = score;
}
}
<强>输出强>
Current Score 10
Current Score 5
Final Score 5
答案 2 :(得分:0)
一般来说,如果超过4-5个类别,我会发明某种表驱动方法。确切地说,这取决于细节(和我的心情),但Enno是一个很好的,也是典型的概念。