Question

CS 1102 Unit 5 – Programming Assignment In this assignment, you will again modify your Quiz...

CS 1102 Unit 5 – Programming Assignment In this assignment, you will again modify your Quiz program from the previous assignment. You will create an abstract class called "Question", modify "MultipleChoiceQuestion" to inherit from it, and add a new subclass of "Question" called "TrueFalseQuestion". This assignment will again involve cutting and pasting from existing classes. Because you are learning new features each week, you are retroactively applying those new features. In a typical programming project, you would start with the full suite of features, enabling you to re-use code in ways natural to Java and avoid cutting and pasting. First create the new "Question" abstract class. • Open your "CS1102" project in Eclipse. • Select "New" -> "Class" from the File menu. • Enter the Name "Question". • Check the box for the "abstract" modifier. • Click "Finish". The new file "Question.java" should appear in the editor pane. Make sure it is also listed under "(default package)" in the "Package Explorer" pane, along with "Quiz.java" and "MultipleChoiceQuestion.java". • If you forgot to check the "abstract" box, add the modifier "abstract" to the "Question" class. public abstract class Question { Add variables and methods to the "Question" class that will be inherited by the subclasses. Copy the following from the "MultipleChoiceQuestion" class and paste them into the "Question" class. • The class variables "nQuestions" and "nCorrect". • The instance variables "question" and "correctAnswer". • The instance method "check". • The class method "showResults". Do not copy the constructor for "MultipleChoiceQuestion" or the instance method "ask". The editor pane for "Question" should now show one error at the statement in "check" that calls the "ask" method. • Add an abstract declaration for the "ask" method. This should be inside the "Question" class but outside all the method definitions. abstract String ask(); Note that this is a method declaration only, with no "{…}", because the method is abstract. It must be defined (implemented) in any concrete (non-abstract) subclasses of "Question". The error warning in the editor pane should disappear. The "ask" call in "check" will use the methods defined in the subclasses of "Question". Now modify the "MultipleChoiceQuestion" class to be a subclass of "Question". • Delete from "MultipleChoiceQuestion" all the variables and methods that you pasted into "Question": "nQuestions", "nCorrect", "question", "correctAnswer", "check", and "showResults". • Do not delete the constructor or the "ask" method. The editor pane should show many errors, particularly in the constructor. • Make "MultipleChoiceQuestion" a subclass of "Question" using the "extends" keyword. public class MultipleChoiceQuestion extends Question { All the error warnings should disappear. Convert "Quiz" to use "Question" variables with "MultipleChoiceQuestion" objects. • Change the type of any "MultipleChoiceQuestion" variables in the main method of "Quiz" to "Question". • But do not change the constructor calls used to initialize these variables. They should still be "MultipleChoiceQuestion". Your program should still work using "Question" variables to reference "MultipleChoiceQuestion" objects. Test it to make sure. Next add a new subclass of "Question" for true/false questions. • Select "New" -> "Class" from the File menu. • Enter the Name "TrueFalseQuestion". • Enter the Superclass "Question". • Click "Finish". The new file "TrueFalseQuestion.java" should appear in the editor pane. • If you did not add the Superclass name, you will need to add "extends Question" to the class declaration. public class TrueFalseQuestion extends Question { The IDE may have already added an empty "ask" method because of the abstract method it found in "Question". It may have also added the annotation "@Override", which is optional and instructs the compiler to make sure the method actually does override a method in a parent class. Add an implementation of the "ask" method that is specific to true/false questions. • Import the "JOptionPane" package. • Like in "ask" for "MultipleChoiceQuestion", have the new "ask" pose the "question" String repeatedly until the user provides a valid answer. • In this case, valid answers are: "f", "false", "False", "FALSE", "n", "no", "No", "NO", "t", "true", "T", "True", "TRUE", "y", "yes", "Y", "Yes", "YES". • When users provide an invalid answer, display the message, "Invalid answer. Please enter TRUE or FALSE." • Convert any valid answer representing true or yes to "TRUE" and any valid answer representing false or no to "FALSE". • Hint: Convert all answers to upper case before checking their validity. Add a "TrueFalseQuestion" constructor to initialize the "question" and "correctAnswer" Strings inherited from "Question". • Give the constructor two String parameters, "question" and "answer". • Use "this" to set the instance variable "question" using the parameter "question". Add the text, "TRUE or FALSE: " to the beginning of the question. this.question = "TRUE or FALSE: "+question; (You could also use "super.question", since the instance variable is in "Question". Either works because "TrueFalseQuestion" does not hide the instance variable in "Question" with its own instance variable named "question".) • Set the instance variable "correctAnswer" to only "TRUE" or "FALSE" based on "answer". Allow the parameter "answer" to be any String that is considered valid by "ask". Now add a true/false question to your quiz! • Initialize a "Question" variable using a "TrueFalseQuestion" constructor. Question question = new TrueFalseQuestion(…); Run your program and test that the following are true. • It accepts only valid answers. • It responds appropriately to correct and incorrect answers. • It provides accurate counts of correct answers and total questions. Finally, add at least four more true/false questions, for a total of at least five multiple-choice questions and five true/false questions. Test your program again

Previous code:

import javax.swing.JOptionPane;

public class MultipleChoiceQuestion {

static int nQuestions = 0;

static int nCorrect = 0;

String question;

String correctAnswer;

MultipleChoiceQuestion(String query, String a, String b, Stringc, String d,

String e, String answer) {

question = query+"\n";

question += "A. "+a+"\n";

question += "B. "+b+"\n";

question += "C. "+c+"\n";

question += "D. "+d+"\n";

question += "E. "+e+"\n";

correctAnswer = answer;

correctAnswer= correctAnswer.toUpperCase();

}

String ask() {

while (true) {

String answer = JOptionPane.showInputDialog(question);

answer = answer.toUpperCase();

boolean valid = (answer.equals("A") || answer.equals("B") ||

answer.equals("C") || answer.equals("D") || answer.equals("E"));

if (valid) return answer;

JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");

}

}

void check() {

nQuestions++;

String answer = ask();

if (answer.equals(correctAnswer)) {

JOptionPane.showMessageDialog(null,"Correct!");

nCorrect++;

} else {

JOptionPane.showMessageDialog(null,"Incorrect. The correct answer

is "+correctAnswer+".");

}

}

void showResults() {

JOptionPane.showMessageDialog(null,nCorrect+" correct out

of"+nQuestions+" questions");

}

}

public class Quiz {

public static void main(String[] args) {

MultipleChoiceQuestion question = new

MultipleChoiceQuestion("What is a quiz?", "a test of knowledge, especially a brief informal test given to

students",

"42",

"a duck",

"to get to the other side",

"To be or not to be, that is the question.",

"a");

question.check();

question.showResults();

MultipleChoiceQuestion question1 = new

MultipleChoiceQuestion("When is a quiz?",

"a long, long ago",

"right now",

"the best of times",

"the worst of times",

"nevermore","b");

question1.check();

question1.showResults();

MultipleChoiceQuestion question2 =

new MultipleChoiceQuestion("Where is a quiz?",

"a galaxy far, far away",

"under the sea",

"right here",

"there and back again",

"the other side of the mountain",

"c");

question2.check();

question2.showResults();

}

}

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

Here is the working code.

Details are added as comments

=====Question.java=====

import javax.swing.JOptionPane;

//Abstract class created using abstract keyword
public abstract class Question {

   static int nQuestions = 0;
   static int nCorrect = 0;
   String question;
   String correctAnswer;
   //The ask function is declared as abstract.
   //Any class extending Question class will require to implement the ask function
   abstract String ask();
  
   void check() {
        nQuestions++;
        String answer = ask();
        if (answer.equals(correctAnswer)) {
          JOptionPane.showMessageDialog(null,"Correct!");
          nCorrect++;
        } else {
          JOptionPane.showMessageDialog(null,"Incorrect. The correct answer is "+correctAnswer+".");
        }
      }
  
   void showResults() {
        JOptionPane.showMessageDialog(null,nCorrect+" correct out of"+nQuestions+" questions");
      }
}

=====MultipleChoiceQuestion.java====

//Modified MultipleChoiceQuestion class, extending abstract class Question

import javax.swing.JOptionPane;

public class MultipleChoiceQuestion extends Question{

   MultipleChoiceQuestion(String query, String a, String b, String c, String d, String e, String answer) {
       question = query+"\n";
       question += "A. "+a+"\n";
       question += "B. "+b+"\n";
       question += "C. "+c+"\n";
       question += "D. "+d+"\n";
       question += "E. "+e+"\n";
       correctAnswer = answer;
       correctAnswer= correctAnswer.toUpperCase();
   }
  
   String ask() {
       while (true) {
           String answer = JOptionPane.showInputDialog(question);
           answer = answer.toUpperCase();
           boolean valid = (answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("D") || answer.equals("E"));
           if (valid) return answer;
           JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
       }
   }
}

======TrueFalseQuestion=====

//Newly created TrueFalseQuestion Class. Extending abstract class Question

import javax.swing.JOptionPane;

public class TrueFalseQuestion extends Question {

   TrueFalseQuestion(String question, String answer) {
       this.question = "TRUE or FALSE: "+question;
       this.correctAnswer = answer;
       correctAnswer= correctAnswer.toUpperCase();
   }
  
   @Override
   String ask() {
       while (true) {
           String answer = JOptionPane.showInputDialog(question);
           //Convert the answer to uppercase, for easy validation
           answer = answer.toUpperCase();
           boolean valid = (answer.equals("F") || answer.equals("FALSE") || answer.equals("N") || answer.equals("NO")
                   || answer.equals("T") || answer.equals("TRUE") || answer.equals("Y") || answer.equals("YES"));
           if (valid) {
               answer = answer.toUpperCase();
               //Convert the answer into TRUE or FALSE.
               //We have used Ternary function. if answer belongs to valid false statements, we return FALSE
               //Else return true
               // return (condition)? true : false
               return (answer.equals("F") || answer.equals("FALSE") || answer.equals("N") || answer.equals("NO")) ? "FALSE" : "TRUE";
           }
           JOptionPane.showMessageDialog(null,"Invalid answer. Please enter TRUE or FALSE.");
       }
   }

}

=====Quiz.java=====

//The Main Class with added question for True or False

public class Quiz {
   public static void main(String[] args) {
        MultipleChoiceQuestion question = new MultipleChoiceQuestion("What is a quiz?", "a test of knowledge, especially a brief informal test given to students", "42", "a duck", "to get to the other side", "To be or not to be, that is the question.", "a");
        question.check();
        question.showResults();
        MultipleChoiceQuestion question1 = new MultipleChoiceQuestion("When is a quiz?", "a long, long ago", "right now", "the best of times", "the worst of times", "nevermore","b");
        question1.check();
        question1.showResults();
        MultipleChoiceQuestion question2 = new MultipleChoiceQuestion("Where is a quiz?", "a galaxy far, far away", "under the sea", "right here", "there and back again", "the other side of the mountain", "c");
        question2.check();
        question2.showResults();
        MultipleChoiceQuestion question3 = new MultipleChoiceQuestion("Which fruit and color has the same name?", "Apple", "Orange", "Grape", "Banana", "Melon", "b");
        question3.check();
        question3.showResults();
        MultipleChoiceQuestion question4 = new MultipleChoiceQuestion("Where is sun located?", "Air", "Water", "Sea", "Forest", "Sky", "e");
        question4.check();
        question4.showResults();
        TrueFalseQuestion trueFalseQuestion = new TrueFalseQuestion("Sky is blue", "TRUE");
        trueFalseQuestion.check();
        trueFalseQuestion.showResults();
        TrueFalseQuestion trueFalseQuestion1 = new TrueFalseQuestion("Sea is red", "FALSE");
        trueFalseQuestion1.check();
        trueFalseQuestion1.showResults();
        TrueFalseQuestion trueFalseQuestion2 = new TrueFalseQuestion("Cricket is a game", "TRUE");
        trueFalseQuestion2.check();
        trueFalseQuestion2.showResults();
        TrueFalseQuestion trueFalseQuestion3 = new TrueFalseQuestion("Dove is an animal", "FALSE");
        trueFalseQuestion3.check();
        trueFalseQuestion3.showResults();
        TrueFalseQuestion trueFalseQuestion4 = new TrueFalseQuestion("Java is a programming language", "TRUE");
        trueFalseQuestion4.check();
        trueFalseQuestion4.showResults();
      }
}

Add a comment
Know the answer?
Add Answer to:
CS 1102 Unit 5 – Programming Assignment In this assignment, you will again modify your Quiz...
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
  • CS 1102 Unit 5 – Programming Assignment In this assignment, you will again modify your Quiz...

    CS 1102 Unit 5 – Programming Assignment In this assignment, you will again modify your Quiz program from the previous assignment. You will create an abstract class called "Question", modify "MultipleChoiceQuestion" to inherit from it, and add a new subclass of "Question" called "TrueFalseQuestion". This assignment will again involve cutting and pasting from existing classes. Because you are learning new features each week, you are retroactively applying those new features. In a typical programming project, you would start with the...

  • Describe how you would develop object-oriented features of Java for the Quiz program developed in the...

    Describe how you would develop object-oriented features of Java for the Quiz program developed in the Programming Assignments. In particular, describe how the program could use each of the following: class variables, instance variables, inheritance, polymorphism, abstract classes, "this", "super", interfaces, and event listeners. Your Discussion should be at least 250 words in length, but not more than 750 words. QUIZ PROGRAM EXAMPLE: Files "QuestionDialog.java": import java.awt.event.*; import javax.swing.*; public class QuestionDialog extends JDialog implements ActionListener { String answer; public...

  • So I am creating a 10 question quiz in Microsoft Visual Studio 2017 (C#) and I...

    So I am creating a 10 question quiz in Microsoft Visual Studio 2017 (C#) and I need help editing my code. I want my quiz to clear the screen after each question. It should do one question at a time and then give a retry of each question that was wrong. The right answer should appear if the retry is wrong. After the 1 retry of each question, a grade should appear. Please note and explain the changes you make...

  • According to the given UML class diagram and classes, complete the missing part of the given...

    According to the given UML class diagram and classes, complete the missing part of the given program by using polymorphism in the main method. In the main method there are: 3 question instances, 1 arraylist for multiple choice answers, 1 arraylist for fill in the blanks answers created. Add those objects to a collection and process the collection. During processing: display the correctAnswer for each question. add the answer to the correct collection: selectionAnswers/textAnswers Specify where the polymorphic behaviours are...

  • PRG/421 Week One Analyze Assignment – Analyzing a Java™Program Containing Abstract and Derived Classes 1.    What is...

    PRG/421 Week One Analyze Assignment – Analyzing a Java™Program Containing Abstract and Derived Classes 1.    What is the output of the program as it is written? (Program begins on p. 2) 2. Why would a programmer choose to define a method in an abstract class (such as the Animal constructor method or the getName()method in the code example) vs. defining a method as abstract (such as the makeSound()method in the example)? /********************************************************************** *           Program:          PRG/421 Week 1 Analyze Assignment *           Purpose:         Analyze the coding for...

  • Update your Assignment 4 as follows (Assignment 4 codes will be on the bottom) Create a...

    Update your Assignment 4 as follows (Assignment 4 codes will be on the bottom) Create a new method called displayAll, that takes an ArrayList (of your base class) as a parameter, and doesn't return anything [25 pts] The displayAll method will loop through the ArrayList, and call the display (or toString) method on each object   [25 pts] In the main method, create an ArrayList containing objects of both your base class and subclass. (You should have at least 4 objects)  [25...

  • Update your Assignment 4 as follows (Assignment 4 codes will be on the bottom) Create a...

    Update your Assignment 4 as follows (Assignment 4 codes will be on the bottom) Create a new method called displayAll, that takes an ArrayList (of your base class) as a parameter, and doesn't return anything [25 pts] The displayAll method will loop through the ArrayList, and call the display (or toString) method on each object   [25 pts] In the main method, create an ArrayList containing objects of both your base class and subclass. (You should have at least 4 objects)  [25...

  • is there anyway you can modify the code so that when i run it i can...

    is there anyway you can modify the code so that when i run it i can see all the song when i click the select button all the songs in the songList.txt file can be shown song.java package proj2; public class Song { private String name; private String itemCode; private String description; private String artist; private String album; private String price; Song(String name, String itemCode, String description, String artist, String album, String price) { this.name = name; this.itemCode = itemCode;...

  • Java Programming Assignment (JavaFX required). You will modify the SudokuCheckApplication program that is listed below. Start...

    Java Programming Assignment (JavaFX required). You will modify the SudokuCheckApplication program that is listed below. Start with the bolded comment section in the code below. Create a class that will take string input and process it as a multidimensional array You will modify the program to use a multi-dimensional array to check the input text. SudokuCheckApplication.java import javafx.application.*; import javafx.event.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.*; public class SudokuCheckApplication extends Application { public void start(Stage primaryStage)...

  • Create an abstract class “Appointment” that represents an event on a calendar. The “Appointment” class will...

    Create an abstract class “Appointment” that represents an event on a calendar. The “Appointment” class will have four instance variables: • An instance variable called “year” which will be of type int • An instance variable called “month” which will be of type int • An instance variable called “day” which will be of type int • An instance variable called “description” which will be of type String The “Appointment” class must also implement the following methods: • A getter...

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