Question

Programming Assignment Objective Write a Java program that utilizes multiple classes. Write a Java program that...

Programming Assignment Objective Write a Java program that utilizes multiple classes. Write a Java program that utilizes inheritance in a practical manner. Problem: Quiz Bowl Your high school quiz bowl team has been losing its edge and needs to find a method to improve. Knowing that you are a savvy programmer, your coach asks you to write a program that the team members can use to hone their skills. Quiz Bowl questions come in three varieties: True/False Multiple Choice (variable number of choices) Short Answer (all answers are a single word) You will write an abstract class Question, that "keeps track of" information common to all three types of questions. All questions will have a String that stores the question as well as a point value. You will then write three classes: QuestionTF, QuestionMC, and QuestionSA, all of which inherit from Question. Your program will be a training program for a single individual. Initially, your program will ask the user to enter their first and last name, followed by the name of the file storing the questions and answers for his/her training session. (The format of this file is discussed on the following page of this program description.) Then, your program should ask the user how many questions they would like for practice. (Your program should prompt the user with the maximum allowed, based on how many questions were in the input file they entered.) Make sure you gracefully handle a situation where the user doesn't enter a valid value or token. Then, your program should prompt the user with the number of random questions from this database that they requested. (Do NOT ask duplicate questions!) The user will have two options: Answer the question Skip the question If the user skips the question, they neither gain nor lose points. If the user answers the question correctly, they gain the number points at which the question is valued. If they answer incorrectly, they lose the same number of points. When answering, to indicate that the user wants to skip the question, they MUST answer "SKIP" (It is guaranteed that no question will have as its correct answer, "SKIP".)You must also create a class called Player, that keeps track of the user playing the game. This class should store the first and last name of the player, as well as the number of points the player has. The player initially starts with 0 points. Finally, you should create a class QuizBowl that contains the main method that gets run. This class may also contain any instance variables and methods you deem necessary. (For example, this class could contain a Player object and an ArrayList of Question objects. In the main of this class, a QuizBowl object would be instantiated.) Question File Format The first line of a question database file will contain a single integer n, the number of questions in the file. The following n sets of data contain information about each question. The first line in each set of data will contain a string that indicates the type of question followed by a positive integer indicating the point value of the question. The string is guaranteed to be one of the three following: "TF", "MC", or "SA". The second line in each set of data will contain a string that is the question. This string will definitely contain spaces – you must read in the whole line in order to read in the whole question. If the question is a true/false question, then the third line of the data set will contain either contain the string "true" or the string "false", depending on the answer to the question. If the question is a short answer question, then the third line of the data set will contain a single string without spaces indicating the answer to the question. If the question is a multiple choice question, then the third line of the data set will contain a single positive integer, k, less than 10, indicating the number of choices for the question. The following k lines will contain each of the possible answers. These answers could have spaces in them – you have to read in the whole line. (These lines will correspond to choices A, B, C, etc.) The last line of a multiple choice question will contain a string storing the correct answer. This string will be a capital letter corresponding to the correct answer choice. (Since there are at most 9 choices, this will always be either "A", "B", "C", "D", "E", "F", "G", "H", or "I".) Sample Input File (sample.txt) 3 TF 5 There exist birds that can not fly. (true/false) trueMC 10 Who was the president of the USA in 1991? 6 Richard Nixon Gerald Ford Jimmy Carter Ronald Reagan George Bush Sr. Bill Clinton E SA 20 What city hosted the 2004 Summer Olympics? Athens Sample Program Run (User's answers in bold.) What is your first name? Arup What is your last name? Guha What file stores your questions? sample.txt How many questions would you like (out of 3)? 5 Sorry, that is too many. How many questions would you like (out of 3)? Two Sorry, that is not valid. How many questions would you like (out of 3)? 3 Points: 10 Question: Who was the president of the USA in 1991? A) Richard Nixon B) Gerald Ford C) Jimmy Carter D) Ronald Reagan E) George Bush Sr. F) Bill Clinton E Correct! You get 10 points. Points: 20 Question: What city hosted the 2004 Summer Olympics? LosAngeles Incorrect, the answer was Athens. You lose 20 points.Points: 5 Question: There exist birds that can not fly. (true/false) SKIP You have elected to skip that question. Arup Guha, your game is over! You final score is -10 points. Better luck next time!

0 0
Add a comment Improve this question Transcribed image text
Answer #1

QuizBowlApp.java

import questionData.MCQ;
import questionData.Question;
import questionData.SA;
import questionData.TF;
import controller.QuizController;
import model.Player;
import model.QuestionMCQ;
import model.QuestionSA;
import model.QuestionTF;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class QuizBowlApp {

    Logger logger = Logger.getLogger(QuizBowlApp.class);
    private int questionNum;
    private BufferedReader br;
    private QuizController quizController=new QuizController();
    private Player player;

    /**
     * Main method that start calling other methods
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        QuizBowlApp obj = new QuizBowlApp();
        obj.getInput();
    }

    /**
     * Function to take player information & input file name
     *
     * @throws Exception
     */
    void getInput() throws Exception {
        br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("First Name : ");
        String fname = br.readLine().toUpperCase();
        System.out.print("Last Name : ");
        String lname = br.readLine().toUpperCase();
        System.out.print("Filename : ");
        String filename = br.readLine().toLowerCase();
        initializeGame(fname, lname, filename);
    }

    /**
     * Function to initialize the player information & to start the quiz bowl
     *
     * @param fname    - first name of player
     * @param lname    - last name of player
     * @param filename - name of file which contain questions & answers
     * @throws Exception
     */
    void initializeGame(String fname, String lname, String filename) throws Exception {
        player = new Player(lname, fname);
        quizController.getFile(filename);
        if (getNumberOfQuestions()) {
            quizBowl();
        }
    }

    /**
     * Function to ask user that how many question he/she want to attend.
     *
     * @return - return boolean flag
     * @throws IOException
     */
    private boolean getNumberOfQuestions() throws IOException {
        boolean flag = false;
        do {
            System.out.print("How many questions would you like (out of "+quizController.getQuestionCount()+" ) ? : ");
            int number = Integer.parseInt(br.readLine());
            if (quizController.getQuestionCount() >= number) {
                questionNum = number;
                flag = false;
            } else {
                flag = true;
                System.out.println("Question count must be less than " + quizController.getQuestionCount());
            }
        } while (flag);
        return true;
    }

    /**
     * Function to start quiz & to call the display for player information
     *
     * @throws Exception
     */
    void quizBowl() throws Exception {
        final String sa = "SA";
        final String mc = "MC";
        final String tf = "TF";
        Question object;
        while (questionNum > 0) {
            object = quizController.getRandomQuestion();
            System.out.println(object.getQuestionType());
            switch (object.getQuestionType()) {
                case tf:
                    checkTFQuestion(object);
                    break;
                case mc:
                    checkMCQquestion(object);
                    break;
                case sa:
                    checkSAQuestion(object);
                    break;
            }
            questionNum--;
        }
        DisplayScore.showScore(player);
    }

    /**
     * Function to get the True False type of question
     *
     * @param object - object of type Question
     * @throws IOException
     */
    public void checkTFQuestion(Question object) throws IOException {
        logger.info("In True False Type Question");
        TF tfData = (TF) object.getQuestion();
        QuestionTF tfobj = new QuestionTF(tfData);
        System.out.println("Points : " + ((TF) object.getQuestion()).getPoint() + "\n" + tfobj.getQuestion());
        checkAnswerAndSetPoint(tfData.getPoint(), tfobj);
    }

    /**
     * Function to get the MCQ type of question & to display the choices
     *
     * @param object - object of type Question
     * @throws IOException
     */
    public void checkMCQquestion(Question object) throws IOException {
        logger.info("In MCQ Type Question");
        MCQ mcqData = (MCQ) object.getQuestion();
        model.Question mcqobj = new QuestionMCQ(mcqData);
        System.out.println("Points : " + ((MCQ) object.getQuestion()).getPoints() + "\n" + mcqobj.getQuestion());
        String[] choices = mcqData.getChoice();
        for (String val : choices)
            System.out.println(val);
        checkAnswerAndSetPoint(mcqData.getPoints(), mcqobj);
    }

    /**
     * Function to get the Short Answer type of question
     *
     * @param object - object of type Question
     * @throws IOException
     */
    public void checkSAQuestion(Question object) throws IOException {
        logger.info("In Short Answer Type Question");
        SA saData = (SA) object.getQuestion();
        model.Question saobj = new QuestionSA(saData);
        System.out.println("Points : " + ((SA) object.getQuestion()).getPoint() + "\n" + saobj.getQuestion());
        checkAnswerAndSetPoint(saData.getPoint(), saobj);
    }

    /**
     * Function to check whether the user input is correct or wrong also to check that user want to skip that question or not
     *
     * @param points      - Current Points of model.Player
     * @param questionObj - Object of type Question to call the checkAnswer method of Question class
     * @throws IOException
     */
    public void checkAnswerAndSetPoint(int points, model.Question questionObj) throws IOException {
        String answer;
        answer = br.readLine().toUpperCase();
        if (answer.equals("SKIP")) {
            System.out.println("You have elected to skip that question.");
            return;
        }
        if (questionObj.checkAnswer(answer, points)) {
            player.setScores(questionObj.getPoints());
            logger.debug("Points : " + player.getScores());
            System.out.println("Correct Answer.. \nPoints Gain : " + questionObj.getPoints() + "\n");
        } else {
            player.setScores(questionObj.getPoints());
            logger.debug("Points : " + player.getScores());
            System.out.println("Wrong Answer.. \nPoints Lose : " + questionObj.getPoints() + "\n");
        }
    }
}


QuizController.java

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Random;
public class QuizController {

    public ArrayList<Question> questionObj = new ArrayList<>();
    public int[] randomNum = null;
    Logger logger = Logger.getLogger(QuizController.class);

    /**
     * Function to Open the File
     *
     * @param filename - Name of file
     * @throws Exception
     */
    public void getFile(String filename) throws Exception
    {
        File file = new File(getClass().getClassLoader().getResource(filename + ".txt").getFile());
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        questionObj = openFile(br);
        logger.info("File Opened Successfully");
        randomNum = new int[questionObj.size()];
    }

    /**
     * Function to get count of questions
     *
     * @return - integer count of question
     */
    public int getQuestionCount() {
        return this.questionObj.size();
    }

    /**
     * Function to fech the questions randomely
     *
     * @return - random questions
     */
    public Question getRandomQuestion() {
        Random random = new Random();
        Question question = null;
        int flag = 0;
        do {
            int temp = random.nextInt(questionObj.size());
            if (randomNum[temp] == 0) {
                question = questionObj.get(temp);
                randomNum[temp] = 1;
                break;
            } else
                flag = 1;
        } while (flag == 1);
        return question;
    }

    /**
     * Function to fech the data from file & insert it into the respective type of Storage classes
     *
     * @param br -bufferReader to read the lines
     * @return - Arraylist of type question which contains objects of respective type of question
     * @throws Exception
     */
    public ArrayList<Question> openFile(BufferedReader br) throws Exception {
        ArrayList<Question> data = new ArrayList<>();
        final String TrueFalse= "TF";
        final String MultipleChoice = "MC";
        final String ShortAnswer = "SA";

        int number = Integer.parseInt(br.readLine());
        while (number > 0) {
            String[] choice = br.readLine().split(" ");
            int points = Integer.parseInt(choice[1]);
            String question = br.readLine();
            logger.info("Question : " + question);
            Question questionObject;
            switch (choice[0]) {
                case TrueFalse:
                    String answertf = br.readLine().toUpperCase();
                    logger.info("Answer : " + answertf);
                    TF tfData = new TF(question, answertf, points);
                    questionObject = new Question(tfData, TrueFalse);
                    data.add(questionObject);
                    break;
                case MultipleChoice:
                    int ChoiceNumber = Integer.parseInt(br.readLine());
                    String[] choices = new String[ChoiceNumber];
                    int i = 0;
                    char ch = 'A';
                    while (ChoiceNumber > 0) {
                        choices[i] = ch + ") " + br.readLine();
                        ch++; i++;
                        ChoiceNumber--;
                    }
                    String answerMCQ = br.readLine().toUpperCase();
                    logger.info("Answer : " + answerMCQ);
                    MCQ mcqData = new MCQ(question, answerMCQ, choices, points);
                    questionObject = new Question(mcqData, MultipleChoice);
                    data.add(questionObject);
                    break;
                case ShortAnswer:
                    String answerSA = br.readLine().toUpperCase();
                    logger.info("Answer : " + answerSA);
                    SA saData = new SA(question, answerSA, points);
                    questionObject = new Question(saData, ShortAnswer);
                    data.add(questionObject);
                    break;
                default:
                    System.out.println("Wrong Choice.");
            }
            number--;
        }
        return data;
    }
}

Player.java

public class Player {
    private String lname, fname;
    private int scores;

    public Player(String lname, String fname) {
        this.lname = lname;
        this.fname = fname;
        this.scores = 0;
    }

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public int getScores() {
        return scores;
    }

    public void setScores(int scores) {
        this.scores = this.scores + scores;
    }

}

Question.java

public class Question {

    private String question, questionType, answers;
    private int points = 0;

    public Question(String question, String questionType) {
        this.question = question;
        this.questionType = questionType;
    }

    public Question() {
    }

    public Boolean checkAnswer(String answer, int points) {
        if (answer.equals(this.answers)) {
            this.points = points;
            return true;
        }
        this.points = -points;
        return false;
    }

    public String getQuestion() {
        return this.question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    public int getPoints() {

        return this.points;
    }

    public void setPoints(int points) {
        this.points = points;
    }

    public String getAnswers() {
        return this.answers;
    }

    public void setAnswers(String answers) {
        this.answers = answers;
    }

    public String getQuestionType() {
        return questionType;
    }

    public void setQuestionType(String questionType) {
        this.questionType = questionType;
    }

}

QuestionMCQ.java

public class QuestionMCQ extends Question {
    private String[] choice;
    private String answer;

    public QuestionMCQ(MCQ mcqObject) {
        super(mcqObject.getQuestion(), "MCQ");
        this.answer = mcqObject.getAnswer();
        this.choice = mcqObject.getChoice();
        this.setAnswers(this.answer);
    }
}

QuestionSA.java

public class QuestionSA extends Question {

    public QuestionSA(SA saObject) {
        super(saObject.getQuestion(), "SA");
        this.setAnswers(saObject.getAnswer());
    }

}

QuestionTF.java

public class QuestionTF extends Question {
    public QuestionTF(TF tfObject) {
        super(tfObject.getQuestion(), "TF");
        this.setAnswers(tfObject.getAnswer());
    }

}

DisplayScore.java

import model.Player;
import org.apache.log4j.Logger;

public class DisplayScore {
    /**
     * Function to display the model.Player Name & the total score of that player
     *
     * @param playerObject - model.Player object which contains overall information about player
     */
    public static void showScore(Player playerObject) {
        Logger logger = Logger.getLogger(DisplayScore.class);
        logger.info("model.Player Name : " + playerObject.getFname() + " Points : " + playerObject.getScores());
        System.out.println("\n" + playerObject.getFname() + " " + playerObject.getLname() +
                ", your game is over!" + "\nYou final score is " + playerObject.getScores() +
                " Points \nBetter luck next time!");
    }
}

MCQ.java
public class MCQ {
    private String question, answer;
    private String[] choice;
    private int points;

    public MCQ(String question, String answer, String[] choice, int points) {
        this.question = question;
        this.answer = answer;
        this.choice = choice;
        this.points = points;
    }

    public String getQuestion() {
        return this.question;
    }

    public String getAnswer() {
        return this.answer;
    }

    public String[] getChoice() {
        return this.choice;
    }

    public int getPoints() {
        return this.points;
    }

}

Question.java

public class Question {
    private Object question;
    private String questionType;

    public Question(Object question, String type) {
        this.question = question;
        this.questionType = type;
    }

    public Object getQuestion() {
        return this.question;
    }

    public String getQuestionType() {
        return this.questionType;
    }
}

SA.java

public class SA {

    private String question, answer;
    private int point;

    public SA(String question, String answer, int points) {
        this.question = question;
        this.answer = answer;
        this.point = points;
    }

    public String getQuestion() {
        return this.question;
    }

    public String getAnswer() {
        return this.answer;
    }

    public int getPoint() {
        return this.point;
    }
}

TF.java
public class TF {

    private String question, answer;
    private int point;

    public TF(String question, String answer, int points) {
        this.question = question;
        this.answer = answer;
        this.point = points;
    }

    public String getQuestion() {
        return this.question;
    }

    public String getAnswer() {
        return this.answer;
    }

    public int getPoint() {
        return this.point;
    }
}

Add a comment
Know the answer?
Add Answer to:
Programming Assignment Objective Write a Java program that utilizes multiple classes. Write a Java program that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 4.3Learning Objective: To read and write text files. Instructions: This is complete program with one Java...

    4.3Learning Objective: To read and write text files. Instructions: This is complete program with one Java source code file named H01_43.java (your main class is named H01_43). Problem: Write a program that prompts the user for the name of a Java source code file (you may assume the file contains Java source code and has a .java filename extension; we will not test your program on non-Java source code files). The program shall read the source code file and output...

  • Programming Assignment 6 Write a Java program that will implement a simple appointment book. The ...

    Programming Assignment 6 Write a Java program that will implement a simple appointment book. The program should have three classes: a Date class, an AppointmentBook class, and a Driver class. • You will use the Date class that is provided on Blackboard (provided in New Date Class example). • The AppointmentBook class should have the following: o A field for descriptions for the appointments (i.e. Doctor, Hair, etc.). This field should be an array of String objects. o A field...

  • JAVA Write a program that prompts the user to enter a file name, then opens the...

    JAVA Write a program that prompts the user to enter a file name, then opens the file in text mode and reads it. The input files are assumed to be in CSV format. The input files contain a list of integers on each line separated by commas. The program should read each line, sort the numbers and print the comma separated list of integers on the console. Each sorted list of integers from the same line should be printed together...

  • JAVA PROGRAM: Guessing Game Objective The student will write an individualized program that utilizes conditional flow...

    JAVA PROGRAM: Guessing Game Objective The student will write an individualized program that utilizes conditional flow of control structures in Java. Specifications For this assignment, you will write a program that guesses a number chosen by your user. Your program will prompt the user to pick a number from 1 to 10. The program asks the user yes or no questions, and the guesses the user’s number. When the program starts up, it outputs a prompt asking the user to...

  • Write a java netbeans program. Project Two, Super Bowl A text file named “SuperBowlWinners.txt” contains the...

    Write a java netbeans program. Project Two, Super Bowl A text file named “SuperBowlWinners.txt” contains the names of the teams that won the Super Bowl from 1967 through 2019. Write a program that repeatedly allows a user to enter a team name and then displays the number of times and the years in which that team won the Super Bowl. If the team entered by the user has never won the Super Bowl, report that to the user instead. For...

  • What to submit: your answers to exercises 2. Write a Java program to perform the following...

    What to submit: your answers to exercises 2. Write a Java program to perform the following tasks: The program should ask the user for the name of an input file and the name of an output file. It should then open the input file as a text file (if the input file does not exist it should throw an exception) and read the contents line by line. It should also open the output file as a text file and write...

  • Objective: Use input/output files, strings, and command line arguments. Write a program that processes a text...

    Objective: Use input/output files, strings, and command line arguments. Write a program that processes a text file by removing all blank lines (including lines that only contain white spaces), all spaces/tabs before the beginning of the line, and all spaces/tabs at the end of the line. The file must be saved under a different name with all the lines numbered and a single blank line added at the end of the file. For example, if the input file is given...

  • M01 PA C++ Classes and Objects INTRODUCTION: Write a C++ program that implements and utilizes a...

    M01 PA C++ Classes and Objects INTRODUCTION: Write a C++ program that implements and utilizes a Stereo Receiver Class/Object. INCLUDE IN YOUR ASSIGNMENT At the top of each of your C++ programs, you should have at least four lines of documentation: Program name (the C++ file name(s)), Author (your name), Date last updated, and Purpose (a brief description of what the program accomplishes). Here is an example: // Program name: tictactoe.cpp // Author: Rainbow Dash // Date last updated: 5/26/2016...

  • Assignment Overview In Part 1 of this assignment, you will write a main program and several...

    Assignment Overview In Part 1 of this assignment, you will write a main program and several classes to create and print a small database of baseball player data. The assignment has been split into two parts to encourage you to code your program in an incremental fashion, a technique that will be increasingly important as the semester goes on. Purpose This assignment reviews object-oriented programming concepts such as classes, methods, constructors, accessor methods, and access modifiers. It makes use of...

  • You will write a single java program called MadLibs. java.

    You will write a single java program called MadLibs. java. This file will hold and allow access to the values needed to handle the details for a "MadLibs" game. This class will not contain a maino method. It will not ask the user for any input, nor will it display (via System.out.print/In()) information to the user. The job of this class is to manage information, not to interact with the user.I am providing a MadLibsDriver.java e^{*} program that you can...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT