aboutsummaryrefslogtreecommitdiff
path: root/Week5 Quiz/src/week5/MCQuestion.java
blob: 86869c58b123a9afa9bc936347e16563e54a4427 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package week5;

import java.util.Random;

/**
 * Class for multiple choice questions
 * 
 * Note: for 2-choice questions the TCQuestion class should be used.
 * 
 * @author Camil Staps, s4498062
 */
public class MCQuestion extends Question {
    
    protected final String[] answers;
    protected final int correctAnswer;
    
    /**
     * Construct a new instance
     * 
     * @param question the question
     * @param answers array of the answer
     * @param correctAnswer index for answers pointing to the correct answer
     * @param weight weight of the question
     */
    public MCQuestion (String question, String[] answers, int correctAnswer, int weight) {
        this.question = question;
        this.answers = answers;
        this.correctAnswer = correctAnswer;
        setWeight(weight);
    }
    
    /** See the javadoc on the constructor above */
    public MCQuestion (String question, String[] answers, int correctAnswer) {
        this.question = question;
        this.answers = answers;
        this.correctAnswer = correctAnswer;
    }

    @Override
    public boolean isCorrect(String answer) {
        return correctAnswer == (answer.charAt(0) - 'A');
    }

    @Override
    public String juisteAntwoord() {
        return answers[correctAnswer];
    }
    
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(super.toString());
        sb.append("\n");
        int i = 0;
        for (String a : answers) {
            sb.append((char) ('A' + i++)).append(": ").append(a).append("\n");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
    
    /**
     * For this type of questions, duplicating randomizes the order of the answers.
     * 
     * @return A new instance of the MCQuestion class with the same parameters, just another order of the answers.
     */
    @Override
    public Question duplicate() {
        Random r = new Random();
        int shift = r.nextInt(answers.length - 1) + 1;
        
        String[] new_answers = new String[answers.length];
        for (String a : answers) {
            new_answers[shift++ % answers.length] = a;
        }
        
        int new_correctAnswer = (correctAnswer + shift) % answers.length;
        
        return new MCQuestion(question, new_answers, new_correctAnswer, weight);
    }
    
}