0

So I am writing a quiz program that contains an uncertain # of questions in it (in Java) and I am having problems accomplishing the following things:

1) loading quiz question from file and storing in arraylist and accessing it (need help!) 2) correct answer not accepted - gives me error (logic error) 3) not all answer choices are displayed

Here's the code:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;

public class Quiz {

 public void writeFile() {
   Question qn = new Question();
   try {
     PrintWriter out = new PrintWriter("quiz.txt");
     out.println(qn.Question);
     out.println(qn.numberOfChoices);
     qn.answerChoices = new String[qn.numberOfChoices];
     for (int i = 0; i < qn.numberOfChoices; i++) {
         out.println(qn.answerChoices[i]);
     }
     out.println(qn.correctAnswer);
     out.println(qn.numOfTries);
     out.println(qn.numOfCorrectTries);
     out.close();
   } catch (IOException f) {
     System.out.println("Error.");
   }
   qn.getQuestion();
 }

 public void readFile() {
     File file = new File ("quiz.txt");
     boolean exists = file.exists();
     Quiz q = new Quiz();
     Question a = new Question();
     List<String> question = new ArrayList<String>();
     String[] answerChoices = a.answerChoices;
     try {
        if (exists == true) {
            Scanner s = new Scanner(file);
            a.Question = s.nextLine();
            a.numberOfChoices = s.nextInt();
            a.answerChoices = new String[a.numberOfChoices];
            for (int i = 0; i < a.numberOfChoices; i++) {
                a.answerChoices[i] = s.nextLine();
            }
            s.nextLine();
            a.correctAnswer = s.nextInt();
            a.numOfTries = s.nextInt();
            a.numOfCorrectTries = s.nextInt();
            a.getQuestion();
         } else {
            q.writeFile();
         }
     } catch (IOException e) {
       System.out.println("File not found.");
     }
 }

public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
    Quiz qz = new Quiz();
    Question b = new Question();
    int Selection;
    List<String> question = new ArrayList<String>();

    System.out.println("Welcome to the Quiz Program! Good luck!");
    do {
       qz.readFile();
       System.out.println("Your answer?: ");
       Selection = in.nextInt();
       if (Selection == b.correctAnswer) {
          b.numOfCorrectTries++;
          b.getQuestion();
       } else {
          b.getQuestion();
       }
    } while (Selection < b.numberOfChoices);
    while (Selection > b.numberOfChoices || Selection < 0) {
       System.out.println("Error. Try again");
       System.out.println("Your answer?: ");
       Selection = in.nextInt();
    }
  }
}

and the question class:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;

public class Question {

 int correctAnswer;
 int numOfTries;
 int numOfCorrectTries;
 int numberOfChoices;
 String Question;
 String[] answerChoices;

 public Question() {

 }
 public void getQuestion() {
    System.out.println("Question: " + Question);
    System.out.println("Answer: ");
    for (int i = 0; i < numberOfChoices; i++) {
        System.out.println(answerChoices[i]);
    }
 }

 public double getPercentageRight() {
     double percentageRight = (numOfCorrectTries / numOfTries) * 100;
     percentageRight = Math.round(percentageRight * 100);
     percentageRight = percentageRight / 100;
     return percentageRight;
 }
}  

QUIZ.TXT:

How many licks does it take to get to the tootsie roll center of a  
tootsie pop?
4
one
two
three
four
2
14
5
What is your name?
3
Arthur, King of the Britons
Sir Lancelot the Brave
Sir Robin the Not-Quite-So-Brave-As-Sir Lancelot
0
14
6
Who's on first?
5
What
Why
Because
Who
I don't know
3
14
7
Which of the following is a terror of the fire swamp?
4
Lightning sand
Flame spurt
R.O.U.S.
All of the above
3
14
4
Who is the all-time greatest pilot?
6
Manfred von Richthofen
Chuck Yeager
Hiraku Sulu
Luke Skywalker
Kara Thrace
Charles Lindbergh
4
14
9
5
  • Are you getting any errors when this code runs? Commented Mar 26, 2016 at 5:59
  • I don't get runtime or compiler error at least for now. it's just not displaying all of the choices when I load the question. it also gives me error when I put the right answer. so essentially a logic error. Commented Mar 26, 2016 at 6:05
  • Can you include a sample quiz.txt file? Commented Mar 26, 2016 at 6:12
  • there's a quiz.txt file here. Commented Mar 26, 2016 at 6:30
  • Can you just specify how you need the output of your java program of this quiz thing??? Commented Mar 26, 2016 at 6:34

2 Answers 2

1

Some issues:

Your List<String> question = new ArrayList<String>(); should instead be something like List<Question> questionBank = new ArrayList<Question>(); since holding everything as a string (instead of a Question object) would be significantly messier. The name questionBank is also more descriptive than question when reading the code. I would also recommend having the questionBank as a class variable so it's easily accessible throughout your Quiz class.

You never add the questions to your ArrayList but I suspect you already know that and it was just low priority while fixing the other issues.

Your Question class is also a bit unconventional. A better way to structure it might be something like this:

public class Question {

     private int correctAnswer;
     private int numOfTries;
     private int numOfCorrectTries;
     private String question;
     private String[] answerChoices;

     public Question(String question, String[] answerChoices,
             int correctAnswer, int numOfTries, int numOfCorrectTries) {
         this.question = question;
         this.answerChoices = answerChoices;
         this.correctAnswer = correctAnswer;
         this.numOfTries = numOfTries;
         this.numOfCorrectTries = numOfCorrectTries;
     }

     public void getQuestion() {
            System.out.println("Question: " + question);
            System.out.println("Answer: ");
            for (int i = 0; i < answerChoices.length; i++) {
                System.out.println(answerChoices[i]);
            }
     }

     public double getPercentageRight() {
         double percentageRight = (numOfCorrectTries / numOfTries) * 100;
         percentageRight = Math.round(percentageRight * 100);
         percentageRight = percentageRight / 100;
         return percentageRight;
     }

}

I removed the variable for numberOfChoices since that is the same as answerChoices.length. I also renamed your Question to question since variables in Java usually follow camelCase. I'm not sure what the other methods are for or how they should display output so I mostly left them alone.

For reading to a file I think you can do something similar to what you have, but I'll post the code I have that conforms to the new constructor for the Question class.

private void addQuestions() {
    File quizText = new File("quiz.txt");
    try {
        Scanner fileIn = new Scanner(quizText);
        while (fileIn.hasNextLine()) {
            String question = fileIn.nextLine();
            int numberOfAnswers = fileIn.nextInt();
            fileIn.nextLine();
            String[] answers = new String[numberOfAnswers];
            for (int i = 0; i < numberOfAnswers; i++) {
                answers[i] = fileIn.nextLine();
            }
            int correctAnswer = fileIn.nextInt();
            int numOfTries = fileIn.nextInt();
            int numOfCorrectTries = fileIn.nextInt();
            fileIn.nextLine();
            Question nextQuestion =
                new Question(question, answers, correctAnswer, numOfTries, numOfCorrectTries);
            questionBank.add(nextQuestion);
        }
        fileIn.close();
    } catch (IOException e){
        e.printStackTrace();
        System.out.println("File Not Found.");
        return;
    }
}

I also made the variables private but you can create a custom getter for them to prevent them from being directly accessed (and/or changed) from the outside. Using this code I was able to create a question bank with all five questions and display the correct answer along with all possible choices so hopefully it points you in the right direction.

Sign up to request clarification or add additional context in comments.

6 Comments

I use List<Question> questionBank = new List<Question> questionBank, but there's an argument mismatch, how would I solve this problem? And also, I load the questions from a file successfully and their answer choices and stuff, but I am not sure how to store them in the arrayList and/or access them from the arrayList. I was wondering how to do this successfully
Since you want an ArrayList you should initialize it like this List<Question> questionBank = new ArrayList<>(); And I strongly recommend making it a class variable so you can access it from within the addQuestions() method. Using the method as I described above will store the Question objects inside the ArrayList. If you want to access the information from the Question class you need to create methods inside that class to do so.
I did, but what if I wanted to put that in my Quiz class instead of my Question class?
The ArrayList definitely belongs in your Quiz class.
So looking at the code, do I need a for loop in my addQuestion() class to add all of the questions to the question class and accessing them. I feel like it might help, but I'm not sure.
|
0

I re-did you quiz class. In my example all your questions stated above is answered. I'll explain them one by one.

public class Quiz {

List<Question> question = new ArrayList<Question>();

public void writeFile() {
    Question qn = new Question();
    try {
        PrintWriter out = new PrintWriter("quiz.txt");
        out.println(qn.Question);
        out.println(qn.numberOfChoices);
        qn.answerChoices = new String[qn.numberOfChoices];
        for (int i = 0; i < qn.numberOfChoices; i++) {
            out.println(qn.answerChoices[i]);
        }
        out.println(qn.correctAnswer);
        out.println(qn.numOfTries);
        out.println(qn.numOfCorrectTries);
        out.close();
    } catch (IOException f) {
        System.out.println("Error.");
    }
    qn.getQuestion();
}

public void readFile() {
    File file = new File("quiz.txt");
    boolean exists = file.exists();
    Quiz q = new Quiz();
    Question a = new Question();
    String[] answerChoices;
    try {
        if (exists == true) {
            Scanner s = new Scanner(file);
            String line = "";
            while (s.hasNextLine()) {
                line = s.nextLine();
                if (line.startsWith("---")) {
                    a = new Question();
                    a.Question = line.substring(4);
                } else if (line.startsWith("choices : ")) {
                    a.numberOfChoices = Integer.parseInt(line.substring(10).trim());
                    a.answerChoices = new String[a.numberOfChoices];
                    for (int i = 0; i < a.numberOfChoices; i++) {
                        a.answerChoices[i] = s.nextLine();
                    }
                } else if (line.startsWith("correct answer : ")) {
                    a.correctAnswer = Integer.parseInt(line.substring(17).trim());

                } else if (line.startsWith("No of Tries : ")) {
                    a.numOfTries = Integer.parseInt(line.substring(14).trim());

                } else if (line.startsWith("No of correct Tries : ")) {
                    a.numOfCorrectTries = Integer.parseInt(line.substring(22).trim());
                    question.add(a);
                }
            }
        } else {
            q.writeFile();
        }
    } catch (IOException e) {
        System.out.println("File not found.");
    }
}

public static void main(String[] args) {
    Quiz qz = new Quiz();
    qz.readFile();
    Question b = new Question();
    int selection;

    //real program starts here
    System.out.println("Welcome to the Quiz Program! Good luck!");
    System.out.println("****************************************");

    b = qz.question.get(2); // you can implement how your questions are taken from list of questions
    b.getQuestion();
    Scanner in = new Scanner(System.in);
    System.out.print("Your answer?: ");
    selection = in.nextInt();

    if (selection == b.correctAnswer) {
        b.numOfCorrectTries++;
        System.out.println("Correct answer");

    } else {
        System.out.println("Incorrect answer");
    }
}

}

1) loading quiz question from file and storing in arraylist and accessing it (need help!)

Instead of using

 List<String> question = new ArrayList<String>();

use below as class variable. So you can access them anywhere inside your class

 List<Question> question = new ArrayList<Question>(); 

2) correct answer not accepted - gives me error (logic error)

Logic is corrected in the main block.

3) not all answer choices are displayed

Re-did you readFile() method. but to be success with this logic you need to recreate your quiz.txt as below.

--- How many licks does it take to get to the tootsie roll center of a tootsie pop?
choices : 4
one
two
three
four
correct answer : 2
No of Tries : 14
No of correct Tries : 5
--- What is your name?
choices : 3
Arthur, King of the Britons
Sir Lancelot the Brave
Sir Robin the Not-Quite-So-Brave-As-Sir Lancelot
correct answer : 0
No of Tries : 14
No of correct Tries : 6
--- Who's on first?
choices : 5
What
Why
Because
Who
I don't know
correct answer :  3
No of Tries : 14
No of correct Tries : 7
--- Which of the following is a terror of the fire swamp?
choices : 4
Lightning sand
Flame spurt
R.O.U.S.
All of the above
correct answer : 3
No of Tries : 14
No of correct Tries : 4
--- Who is the all-time greatest pilot?
choices : 6
Manfred von Richthofen
Chuck Yeager
Hiraku Sulu
Luke Skywalker
Kara Thrace
Charles Lindbergh
correct answer : 4
No of Tries : 14
No of correct Tries : 9

Note : Selection of the question is based on

   b = qz.question.get(2);

in the main(). To create a question paper based on randomly selected questions, you might create a separate method and prompt questions from this method. Refer Math.random() further.

Also better to create an XML file instead of txt for this kind of applications. Google for "Java and XML"

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.