0

This is my first post but I'll get to the point.

I'm attempting to make a quiz in Java. My application, in its current state, reads questions from a text file, splits the questions by newline, returns the data and iterates through the list with a Scanner to check input for comparison with a stored answer...well, not quite yet the latter bit.

Everything works fine but the catch is I've only got the questions. I can't wrap my head around how to structure the questions AND answers in a text file and then breaking it down into some sort of array structure that could be presented to the user in the console.

So, basically, I want to store the questions, the answer choices and the correct answer all on one line...or however I could do all three in an efficient way. I'm assuming I would break by newline, then break by some other character to separate the three parts that I need from each line. Where do I go from there and how? How would I keep track of the which goes where once I break it all up?

My apologies for the short-story approach. I've looked everywhere for a guide or tutorial to fit my needs. I should warn you, too...I'm pretty new to Java and I know there's a better way to do what I need so, please...break it down for me in a way a newcomer could understand.

I hope all of this made sense. If this is duplicated elsewhere or too broad, please direct me where to go so that I may learn. Anyway, here's my code!

QuestionArray.java

import java.util.ArrayList;
public class QuestionArray {
    private static ArrayList<String> list = new ArrayList<String>();
    public static Object[] processFile() {
        String file = FileStuff.fileAsString("res/questions/questions.txt");
        String[] lines = file.split("\n");
        for (int i = 0; i < lines.length; i++) {
            list.add(lines[i]);
        } return list.toArray();
    }
}

FileStuff.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
public class TextFileStuff {
    public static String fileAsString(String path) {
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(path));
            String line;
            while((line = br.readLine()) != null)
                builder.append(line + "\n");
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        } return builder.toString();
    }
}

Quiz.java

import java.util.Scanner;
public class Quiz {
    private static Object[] questionArray;
    public static void main(String[] args) {
        questionArray = QuestionArray.processFile();
        takeTheQuiz(questionArray);
    }
    public static void takeTheQuiz(Object[] questions) {
        int score = 0;
        Scanner userInput = new Scanner(System.in);
        for(int i = 0; i < questions.length; i++) {
            System.out.println(questions[i]);
            String answer = userInput.nextLine().toLowerCase();
            if(answer.equals("")) {
                score++;
            }
        } 
        System.out.println("You scored "+score+" out of "+questions.length); 
        if(score <= 2) {
            System.out.println("You suuuuck."); 
        } else {
            System.out.println("Mediocre performance.");
        }
        userInput.close();
    }
}
  • why do you not use a delimiter that would not normally appear in your text? – Scary Wombat Mar 12 at 0:57
  • @ScaryWombat I mention using another delimiter in the third paragraph as an assumption. I guess my main concern is how to go from splitting from that delimiter to presenting it in the console. I can split a text file by newline just fine. I just don't know how or what classes to use to achieve my desired end result. – B. Richards Mar 12 at 1:02
  • You could use a Map with the key being the question and the value being the answer - is this what you are asking? – Scary Wombat Mar 12 at 1:08
  • @ScaryWombat Thanks for the reply. Could you post a little pseudo code so I could get a better idea? – B. Richards Mar 12 at 16:32
0

First you need to decide the structure of your text file. Here is how you can do it.

Sample text file:

3
%%%
@@@ 
&&&
What is Java?%%%a. Food@@@b. Programming Language@@@c. Person%%%b
Is this a question?%%%a. Yes@@@b. No@@@c. Maybe%%%a
Are you correct?%%%a. Yes@@@b. No@@@c. Maybe%%%c

The 3 is the number of questions inside the file
The %%% is the delimiter for the parts of the question
The @@@ is the delimiter for the parts of the choices
The &&& is the delimiter for the parts of the answers (in case there are questions with multiple answers)
The succeeding parts are the questions. The format is: (question part)%%%(choice part)%%%(answer part)

Since there are many possible choices, you can format the possible choice like this: (choice a)@@@(choice b)@@@(choice c) this is the (choice part) from above.

Since there are maybe many possible answers, you can format the possible answers like this: (answer a)@@@(answer b)@@@(answer c) this is the (answer part) from above.

Once you have decided how your text file looks, you can make a class that will hold those questions, choices and answers. An example is this:

public class Question {
    private String question; // This will hold the question
    private String[] choices;// This will hold the choices
    private String[] answers;// This will hold the correct answer/s, I made it an array since there might be
                                // a question that has multiple answers

    public Question(String question, String[] choices, String[] answers) {
        this.question = question;
        this.choices = choices;
        this.answers = answers;

    }

    /**
     * @return the question
     */
    public String getQuestion() {
        return question;
    }

    /**
     * @param question
     *            the question to set
     */
    public void setQuestion(String question) {
        this.question = question;
    }

    /**
     * @return the choices
     */
    public String[] getChoices() {
        return choices;
    }

    /**
     * @param choices
     *            the choices to set
     */
    public void setChoices(String[] choices) {
        this.choices = choices;
    }

    /**
     * @return the answer
     */
    public String[] getAnswers() {
        return answers;
    }

    /**
     * @param answer
     *            the answer to set
     */
    public void setAnswer(String[] answer) {
        this.answers = answer;
    }

}

Now that you have a class that will hold those questions, choices and answers. You then will make a reader class that will read and transfer all those information to your question class. Here is an example:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TextFileStuff {

    public static Question[] fileAsString(String path) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(path));
            String line = br.readLine(); // get the number of questions
            Question[] questionList = new Question[Integer.parseInt(line)]; // initialize the question array
            String partsDelimiter = br.readLine(); // get the delimiter for the question parts
            String choicesDelimiter = br.readLine(); // get the delimiter for the choices
            String answersDelimiter = br.readLine(); // get the delimiter for the answers
            int questionNumber = 0; // initialize the question number
            while ((line = br.readLine()) != null) { // loop through the file to get the questions
                if (!line.trim().isEmpty()) {
                    String[] questionParts = line.split(partsDelimiter); // split the line to get the parts of the
                                                                            // question
                    String question = questionParts[0]; // get the question
                    String[] choices = questionParts[1].split(choicesDelimiter); // get the choices
                    String[] answers = questionParts[2].split(answersDelimiter); // get the answers
                    Question q = new Question(question, choices, answers); // declare and initialize the question
                    questionList[questionNumber] = q; // add the question to the question list
                    questionNumber++; // increment the question number
                }
            }
            br.close();

            return questionList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Now that you have all the needed parts what's left to do is to make the main method and present those question into the user. You can do it like this:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String path ="\\Test\\src\\res\\questions.txt"; // the path of the text file
                                                                                            // that contains the
                                                                                            // questions
        Question[] questionList = TextFileStuff.fileAsString(path);
        takeTheQuiz(questionList);
    }

    public static void takeTheQuiz(Question[] questions) {
        int score = 0;
        Scanner userInput = new Scanner(System.in);
        for (int i = 0; i < questions.length; i++) {
            System.out.print("======================");
            System.out.print("Question " + (i + 1));
            System.out.println("======================");
            System.out.println(questions[i].getQuestion()); // Print the question
            String[] choices = questions[i].getChoices(); // get the choices
            for (int j = 0; j < choices.length; j++) { // loop through the choices
                System.out.println(choices[j]); // Print the choices
            }
            System.out.print("Input an answer : "); // Print the choices
            String answer = userInput.nextLine().toLowerCase();
            String[] answers = questions[i].getAnswers(); // get the answers
            for (int j = 0; j < answers.length; j++) { // loop through the answers
                if (answer.equals(answers[j])) { // check if the user's answer is correct
                    score++; // increment score
                }
            }
        }
        System.out.println("You scored " + score + " out of " + questions.length);
        if (score == questions.length) {
            System.out.println("Cheater!");
        } else if (score <= 2) {
            System.out.println("You suuuuck.");
        } else {
            System.out.println("Mediocre performance.");
        }
        userInput.close();
    }

}

Here is the sample output of the program:

======================Question 1======================
What is Java?
a. Food
b. Programming Language
c. Person
Input an answer : a
======================Question 2======================
Is this a question?
a. Yes
b. No
c. Maybe
Input an answer : v
======================Question 3======================
Are you correct?
a. Yes
b. No
c. Maybe
Input an answer : a
You scored 0 out of 3
You suuuuck.

Now you have a somewhat dynamic question and answer program. If you want to add/delete a question then you will just have to modify the text file. Feel free to comment for clarifications and questions.

  • I had made a bunch of comments but I should have read through the code better. Thank you for the detailed response, this answers my question! – B. Richards Mar 12 at 16:46

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.