Building a Trivia Game in Java

A neon question mark at the end of a dark hallway




Today I built a Java Trivia Game with my students, and I want to walk through how we solved it.

First, we set out the steps for the game:

1. The game will have ten questions.
2. There will be two players.
3. The order will alternate between player one and player two.
4. Each correct answer earns a point, whereas incorrect answers just don't count.
5. Whoever has the most points in the end wins. (We haven't decided what to do with ties yet).


Starting out, we knew that we would need to make use of a text file and a scanner:


Scanner scan = new Scanner(new File("questions.txt"));


In questions.txt, I started off with a number that would signify the number of questions included and then the rest in the following format:

Question:
Answer Choice 1
Answer Choice 2
Answer Choice 3
Answer Choice 4
Correct Answer

This allowed me to easily pull out each question and create an object instance of it. The class for questions looks like this:



public class Question {

  String question = null;
  //Answer choices
  String answerOne = null;
  String answerTwo = null;
  String answerThree = null;
  String answerFour = null;
  //Correct answer
  String correctAnswer = null;

  public Question(String question, String answerOne, String answerTwo,
  String answerThree, String answerFour, String correctAnswer) {

    this.question = question;
    //Answer choices
    this.answerOne = answerOne;
    this.answerTwo = answerTwo;
    this.answerThree = answerThree;
    this.answerFour = answerFour;
    //Correct answer
    this.correctAnswer = correctAnswer;
  }
}


This works well for the questions, as now I can quickly add them to an ArrayList so that they can be accessed efficiently.
I created the ArrayList of questions like this:


int numQuestions = Integer.parseInt(scan.nextLine());
for(int i = 0; i < numQuestions; i++) { questions.add(new Question(scan.nextLine(),      scan.nextLine(), scan.nextLine(), scan.nextLine(), scan.nextLine(), scan.nextLine())); }



Now with a full list of questions, all that was left to do was play out the actual game. That code is a but longer than I would like to feature here, but I will include the link to the project on GitHub. Today was all about reading from files and using data structures. My students completed this project with the use of pair-programming, so it was a huge success of a day!

Trivia Game Repository on GitHub

Comments