/** * Holds a trivia or quiz question, a list of possible answers, * and the index of the correct answer. Indexes passed as parameters * to Question methods start indexing at 0. * * @author Zach Tomaszewski * @version Nov 21, 2007 */ public class Question { protected String question; protected String[] answers; protected int correctIndex; //index of correct answer in answers array /** * Creates a new Question. * * @param question The question. * @param answers A list of answers. * @param correct The index of the correct answer in answers; * must be >= 0 and < answers.length * * @throws IndexOutOfBoundsException If correct index is out of range. * @throws NullPointerException If answer list is null. */ public Question(String question, String[] answers, int correct) throws IllegalArgumentException { if (correct < 0 || correct >= answers.length) { throw new IndexOutOfBoundsException("Correct answer index out of range."); } this.question = question; this.answers = answers; this.correctIndex = correct; } /** * Returns the index of the correct answer. */ public int getCorrect() { return this.correctIndex; } /** * Returns whether the given answerIndex corresponds to the correct * answer to this question. * * @throws IndexOutOfBoundsException If answerIndex is not within range * of a possible answer. */ public boolean isCorrect(int answerIndex) throws IndexOutOfBoundsException { if (answerIndex < 0 || answerIndex >= this.answers.length) { throw new IndexOutOfBoundsException("Given answer index out of range."); }else { return (answerIndex == this.correctIndex); } } /** * Returns a string representation of this question, * which displays a question followed by a numbered list * of answers. Note that displayed numbering starts at 1. *
* Example: *
* Question. * 1. first answer * 2. second answer * 3. third answer **/ public String toString() { String result = this.question + "\n"; for (int i = 0; i < answers.length; i++) { result += (i + 1) + ". " + answers[i] + "\n"; } return result; } }