Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a java applicaiton that creates a quiz application that asks the user 5 m

ID: 3840236 • Letter: C

Question

Create a java applicaiton that creates a quiz application that asks the user 5 multiple choice questions, prompts for an answer, then advises the user if their answer is correct or incorrect. If the user provides the wrong answer the application should provide the user with the correct answer. After the user completes the 5 questions the application should provide the user with a summary of their results including the number of correct and incorrect answers as well as their score (percent). Your application must contain and use at least two custom methods in addition to the main method. Quiz questions and answers must be read from a file named quiz.txt that is placed in the same folder as the java file being executed. The quiz.txt file should contain 10 question & answer combinations. The 5 questions asked should be randomly selected from the questions in this file. You can choose to structure the contents of your quiz.txt file in any way you wish but keep in mind that it should be easy to add additional questions. (It is not part of this exercise, but you should consider how the file should be structured so that questions can be programmatically added and removed.) For this exercise the questions can be on any topic (ie. state capitals) but your application should be built in such a way that the subject of the questions is irrelevant

Here is a sample question:

What is the state capital of Connecticut:

A. Bridgeport

B. Bristol

C. Hartford

D. Norwalk

Explanation / Answer

Program Code to copy:

// QuestionAnswer.java

/**

* Class to maintain each quiz question, corresponding options and the correct answer

*/

import java.util.List;

public class QuestionAnswer

{

     String question;

     List<String> answers;

     String correctAnswer;

     public QuestionAnswer()

     {

          this.question = null;

          this.answers = null;

          this.correctAnswer = null;

     }

     public QuestionAnswer(String question, List<String> answers, String correctAnswer)

     {

          this.question = question;

          this.answers = answers;

          this.correctAnswer = correctAnswer;

     }

     public String getQuestion()

     {

          return question;

     }

     public void setQuestion(String question)

     {

          this.question = question;

     }

     public List<String> getAnswers()

     {

          return answers;

     }

     public void setAnswers(List<String> answers)

     {

          this.answers = answers;

     }

     public String getCorrectAnswer()

     {

          return correctAnswer;

     }

     public void setCorrectAnswer(String correctAnswer)

     {

          this.correctAnswer = correctAnswer;

     }

     public String toString()

     {

          String result = "";

          result += question + " ";

          for (String str : answers)

              result += str + " ";

          return result;

     }

}

// QuizTest.java

// import the required classes

import java.util.*;

import java.io.*;

/**

* Program that contains the logic to play the quiz for 5 random questions

* picked from

*/

public class QuizTest

{

     // main() method to that starts the execution of the quiz game

     public static void main(String args[])

     {

          // Define a Set class reference of type QuestionAnswer which holds the

          // HashSet object. This is used to hold the QuestionAnswer class

          // objects

          Set<QuestionAnswer> sqa = new HashSet<QuestionAnswer>();

          // the iterative variable used in the loop

          int i = 0;

          // to maintain the number of questions

          int count = 5;

          // define QuestionAnswer object by using default constructor

          QuestionAnswer qa = new QuestionAnswer();

          // define a string to hold the file name

          String fileName = "quiz.txt";

          // loop that keeps count of the number of questions added to the set

          while (i < count)

          {

              // call the getQuestion() by passing the file name and store the

              // return QuestionAnswer

              // object into qa

              qa = getQuestion(fileName);

              // condition to check whether the object qa is present in sqa

              // call the method doesContainObject() by passing the Set object

              // sqa

              // and QuestionAnswer object qa. Depending on the returned

              // boolean value

              // add the object qa to the object sqa.

              // Increment the iterative value

              if (!doesContainObject(sqa, qa))

              {

                   // add qa to sqa

                   sqa.add(qa);

                   i++;

              }

          }

          // Once the loop got the random 5 questions, then call the

          // processQuiz() by passing

          // sqa object and count

          processQuiz(sqa, count);

     }

     // processQuiz(): This accepts a Set object and a int variable

     // This method is used to display the question and prompt the user for the

     // answer. This is repeated for 5 questions. It keeps updating the number

     // of correct

     // answered and number of wrong answers answered.

     public static void processQuiz(Set<QuestionAnswer> sqa, int totalQuestions)

     {

          // define an iterator for the Set sqa object

          Iterator<QuestionAnswer> iterate = sqa.iterator();

          // variables to maintain the # correct and # wrong answers

          int correctAns = 0, wrongAns = 0;

          // define string to hold user input

          String answer = null;

          // to hold the question

          String question = null;

          // define a list to store the options for the respective question

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

          // define QuestionAnswer object to null

          QuestionAnswer quiz = null;

          // Scanner object to read the input from the console(user)

          Scanner readIn = new Scanner(System.in);

          // variable to maintain the question number

          int i = 1;

          // loop until there are no more objects in the iterator iterate

          while (iterate.hasNext())

          {

              // get the object from the iterate

              quiz = iterate.next();

              // get the question from the object quiz

              question = quiz.getQuestion();

              // get the list of options from the object quiz

              options = quiz.getAnswers();

              // display the question

              System.out.println(i + ") " + question);

              // loop to display the options

              for (String opt : options)

              {

                   System.out.println(" " + opt);

              }

              // prompt the user for the answer

              System.out.print("Your option is: ");

              // read the answer

              answer = readIn.next().toUpperCase();

              // condition to check whether the user input matches with the

              // answer present in the object quiz

              if (answer.equals(quiz.getCorrectAnswer()))

              {

                   // if matches, increment the correctAns variable

                   correctAns++;

              }

              // otherwise

              else

              {

                   // display the correct answer

                   System.out.println(" Wrong Answer! The correct answer is: "

                             + quiz.getCorrectAnswer());

                   // increment the wrongAns

                   wrongAns++;

              }

              // increment the question number

              i++;

              // to provide an empty line after each question

              System.out.println();

          }

          // if all the questions are answered, then print the status

          printStatus(correctAns, wrongAns, totalQuestions);

     }

     // printStatus(): This accepts three int variables

     // 1. correct : holds the #of correct answers

     // 2. wrong: holds the #of wrong answers

     // 3. totalQuestions: hold the #of questions asked

     // This method is used to display the status

     public static void printStatus(int correct, int wrong, int totalQuestions)

     {

          // calculate the pass percentage

          double percent = correct / (double) totalQuestions * 100;

          // display #of correct answers

          System.out.println("Number of correct answers: " + correct);

          // display #of wrong answers

          System.out.println("Number of wrong answers : " + wrong);

          // display the pass percent

          System.out.println("Percentage pass          : " + percent + "%");

     }

     // doesContainObject(): This accepts Set object and QuestionAnswer object

     // Returns a boolean value.

     // This method checks whether the question in the qa exists in the sqa

     // question

     public static boolean doesContainObject(Set<QuestionAnswer> sqa, QuestionAnswer qa)

     {

          // define a Iterator for the sqa object

          Iterator<QuestionAnswer> iterate = sqa.iterator();

          // loop until no more elements in the sqa

          while (iterate.hasNext())

          {

              // condition to check the qa question exists in the sqa question

              if (iterate.next().getQuestion().equals(qa.getQuestion()))

                   // if exists, return true

                   return true;

          }

          // if question does not exits in sqa then return false

          return false;

     }

     // getQuestion() : This accepts a String object which holds the file name

     // Returns the QuestionAnswer object

     public static QuestionAnswer getQuestion(String fileName)

     {

          // define a random object

          Random randline = new Random();

          // define an index

          int index = 0;

          // declare the Scanner reference

          Scanner sc;

          // define the QuestionAnswer object

          QuestionAnswer quesAns = new QuestionAnswer();

          // define String to read the question from the text file

          String question = null;

          // define List to read the options from the text file

          List<String> answers = null;

          // define String to read the correctAnswer from the text file

          String correctAns = null;

          // since file concept is used, place the logic in try..catch block

          try

          {

              // define the Scanner object to point to the file

              sc = new Scanner(new File(fileName));

              // loop until the sc points to end of the file

              while (sc.hasNextLine())

              {

                   // increment the index value

                   ++index;

                   // define the ArrayList object

                   answers = new ArrayList<String>();

                   // read the question

                   question = sc.nextLine();

                   // loop to read the options from the text file

                   // and add it to the list answers

                   for (int i = 0; i < 4; i++)

                   {

                        answers.add(sc.nextLine());

                   }

                   // read the correct answer from the text file

                   correctAns = sc.nextLine();

                   // condition to check whether the random value

                   // at specific index is 0 or not

                   if (randline.nextInt(index) == 0)

                        // if true, define the QuestionAnswer object

                        quesAns = new QuestionAnswer(question, answers, correctAns);

              }

              // / close the scanner object

              sc.close();

          }

          // catch the exception

          catch (FileNotFoundException e)

          {

              e.printStackTrace();

          }

          // return the QuestionAnswer object

          return quesAns;

     }

}

Sample Output:

1) What is the state capital of Montana?

     A. Carson City

     B. Montgomery

     C. Helena

     D. Trenton

Your option is: A

Wrong Answer! The correct answer is: C

2) What is the state capital of Nebraska?

     A. Little Rock

     B. Phoenix

     C. Lincoln

     D. Helena

Your option is: B

Wrong Answer! The correct answer is: C

3) What is the state capital of New Hampshire?

     A. Carson City

     B. Trenton

     C. Concord

     D. Little Rock

Your option is: C

4) What is the state capital of Arizona?

     A. Phoenix

     B. Concord

     C. Helena

     D. Montgomery

Your option is: D

Wrong Answer! The correct answer is: A

5) What is the state capital of Alaska?

     A. Helena

     B. Juneau

     C. Montgomery

     D. Concord

Your option is: B

Wrong Answer! The correct answer is: C

Number of correct answers: 1

Number of wrong answers : 4

Percentage pass          : 20.0%

Sample Input file: quiz.txt

What is the state capital of Alabama?

A. Concord

B. Montgomery

C. Helena

D. Juneau

B

What is the state capital of New Jersey?

A. Trenton

B. Helena

C. Carson City

D. Sacramento

A

What is the state capital of Nevada?

A. Carson City

B. Montgomery

C. Helena

D. Trenton

A

What is the state capital of Arkansas?

A. Little Rock

B. Helena

C. Phoenix

D. Sacramento

A

What is the state capital of Arizona?

A. Phoenix

B. Concord

C. Helena

D. Montgomery

A

What is the state capital of Alaska?

A. Helena

B. Juneau

C. Montgomery

D. Concord

C

What is the state capital of California?

A. Sacramento

B. Phoenix

C. Juneau

D. Little Rock

A

What is the state capital of Nebraska?

A. Little Rock

B. Phoenix

C. Lincoln

D. Helena

C

What is the state capital of Montana?

A. Carson City

B. Montgomery

C. Helena

D. Trenton

C

What is the state capital of New Hampshire?

A. Carson City

B. Trenton

C. Concord

D. Little Rock

C

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote