Alexandros Papadopoulos Alexandros Papadopoulos - 25 days ago 9
Java Question

Java: Which structure to use for a multiple choice game

I'm trying to create a multiple choice game with 4 possible answers for each question.

During the main part of the game the player will be asked a question and will be prompted to input an answer.

In my code, along with the question and answer String, I will somehow need to be able to tell which is the correct answer and maybe even flag the question so as to not be repeated in later rounds. Also the possible answers need to be in randomized/different order between "playthroughs".

I'm trying to figure out what data structure to use to store all of the above, as to be able to write the code appropriately.

My first choice would be to have a main

Hashmap<String, HashMap>
and a second
HashMap<String, Boolean>
* that is stored into the first one. The first map will store the question strings as keys and the second HashMap(s) as values. The second HashMap will store the answers as keys and a boolean for each key, indicating which one is the correct answer, as value.

Kind of complicated but at least in theory it seems to work, although I still don't have a way to mark a question as "already asked".

My second choice would be a two dimensional array whose lines will represent a question, the 0 column being the question Strings, the 1,2,3,4 columns storing the answer strings, the 5 column storing the correct answer string, and maybe have a 7th column (6) storing a flag, marking if the question hasn't been asked already.

Although simpler in theory I fear this method would be really confusing to actually code with.

If there are better/easier ways to do this please tell me and maybe even elaborate on their benefits.

Answer

Java is an Object-Oriented language. You should use it.

Example: Create a class representing a question and the possible answers.

public class Question {
    private String       question;
    private String       correctAnswer;
    private List<String> answerList;
}

Now, you can create a good useful constructor, where you give the question first, then all the answers using varargs, with the correct answer first:

new Question("How satisfied are you with this answer?",
             "Extremely satisfied",
             "Very satisfied",
             "Somewhat satisfied",
             "Not so satisfied");

Your constructor could then build the answers list and call Collections.shuffle(this.answers) to randomize them.

You then add all the questions to a List<Question> and call shuffle on that, so questions will be asked in random order, and only once.