Question

In: Computer Science

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

CS 1102 Unit 5 – Programming AssignmentIn 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.

my code :

MultipleChoiceQuestion.java

package quiz;

import javax.swing.JOptionPane;

public class MultipleChoiceQuestion {

   static int nQuestions = 0;

   static int nAnswers = 0;

   String question;

   String correctAnswer;

   public 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.toUpperCase();

   }

   public String ask() {

       return JOptionPane.showInputDialog(question);

   }

   public void check() {

       // we were told to take off while loop but while loop here will help us keep if
       // we give invalid answer,

       // but given incorrect answer it will ask the next question.

       nQuestions += 1;

       while (true) {

           String answer = (ask());

           answer = answer.toUpperCase();

           if (answer.equals(correctAnswer)) {

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

               nAnswers += 1;

               return;

           }

           else if (answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("D")
                   || answer.equals("E")) {

               JOptionPane.showMessageDialog(null, "Inorrect.");

               return;

           }

           else {

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

           }

       }
   }

   static void showResults() {

       JOptionPane.showMessageDialog(null,
               "Number of questions asked " + nQuestions + ". The number of correct answers given are " + nAnswers);

   }
}

my code :

Quiz.java

package quiz;

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();

       // you can construct more MultipleChoiceQuestion objects by pasisng values based
       // on its parameterized constructor

       question = new MultipleChoiceQuestion("What are the variables required to calculate heat input?", "Ampere",
               "Voltage", "Travel speed", "Understanding if it's in KJ/in. or J/in.", "All of the above", "E");

       question.check();

       question = new MultipleChoiceQuestion("how many earth years does it take pluto to go around the sun?", "50 yrs",
               "124 yrs", "165 yrs", "248 yrs", "40000 years", "d");

       question.check();

       question = new MultipleChoiceQuestion("comic book time: who is the fastest man alive?", "Barry Allen",
               "Wally West", "Batman", "Usain Bolt", "ME", "a");

       question.check();

       question = new MultipleChoiceQuestion("what is 10*10?", "10", "1000", "100", "1", "IDK", "c");

       question.check();

       MultipleChoiceQuestion.showResults();

   }

}

Solutions

Expert Solution

// After Updating all class:

---------------------------------------------------Question.java :

/*here I comment check2() function if you not understand changes in check(), prefer to

see check2()

*/

import javax.swing.JOptionPane;

public abstract class Question {
   static int nQuestions = 0;
   static int nAnswers = 0;
   String question;
   String correctAnswer;
  
   public abstract String ask();
  
   /*public void check2() {
       nQuestions += 1;
       while (true) {
           String answer=(ask());
           answer = answer.toUpperCase();
           if(answer.equals("TRUE") || answer.equals("T") || answer.equals("YES") || answer.equals("Y") )
           answer = "TRUE";
           else if(answer.equals("FALSE") || answer.equals("F") || answer.equals("NO") || answer.equals("N") )
               answer="FALSE";
           if (answer.equals(correctAnswer)) {
   JOptionPane.showMessageDialog(null, "Correct!");
   nAnswers += 1;
   return;
   }
           else if (answer.equals("TRUE") || answer.equals("FALSE") ) {
   JOptionPane.showMessageDialog(null, "Inorrect.");
   return;
   }
   else {
   JOptionPane.showMessageDialog(null, "Invalid answer. Please enter TRUE or FALSE.");
   }
       }
   }//*/
  
  
   public void check() {

   // we were told to take off while loop but while loop here will help us keep if
   // we give invalid answer,

   // but given incorrect answer it will ask the next question.

   nQuestions += 1;

   while (true) {
   String answer = (ask());
   answer = answer.toUpperCase();
   if(answer.equals("TRUE") || answer.equals("T") || answer.equals("YES") || answer.equals("Y") )
               answer = "TRUE";
   else if(answer.equals("FALSE") || answer.equals("F") || answer.equals("NO") || answer.equals("N") )
                   answer="FALSE";
     
   if (answer.equals(correctAnswer)) {
   JOptionPane.showMessageDialog(null, "Correct!");
   nAnswers += 1;
   return;
   }
   else if (answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("D")
   || answer.equals("E")) {
   JOptionPane.showMessageDialog(null, "Inorrect.");
   return;
   }
   else if (answer.equals("TRUE") || answer.equals("FALSE") ) {
   JOptionPane.showMessageDialog(null, "Inorrect.");
   return;
   }
   else if(correctAnswer.equals("TRUE") || correctAnswer.equals("FALSE")){
   JOptionPane.showMessageDialog(null, "Invalid answer. Please enter TRUE or FALSE.");
   }
   else {
   JOptionPane.showMessageDialog(null, "Invalid answer. Please enter A, B, C, D, or E.");
   }
   }
   }

   static void showResults() {
   JOptionPane.showMessageDialog(null,
   "Number of questions asked " + nQuestions + ". The number of correct answers given are " + nAnswers);
   }

}

---------------------------------------------------Quiz.java


public class Quiz {

   public static void main(String[] args) {
       Question question=new TrueFalseQuestion("Is this a good platform", "TRUE");
      
       question.check();
      
       TrueFalseQuestion.showResults();
       //*/
       /*
       Question 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 = new MultipleChoiceQuestion("What are the variables required to calculate heat input?", "Ampere",
   "Voltage", "Travel speed", "Understanding if it's in KJ/in. or J/in.", "All of the above", "E");

   question.check();

   question = new MultipleChoiceQuestion("how many earth years does it take pluto to go around the sun?", "50 yrs",
   "124 yrs", "165 yrs", "248 yrs", "40000 years", "d");

   question.check();

   question = new MultipleChoiceQuestion("comic book time: who is the fastest man alive?", "Barry Allen",
   "Wally West", "Batman", "Usain Bolt", "ME", "a");

   question.check();

   question = new MultipleChoiceQuestion("what is 10*10?", "10", "1000", "100", "1", "IDK", "c");

   question.check();

   MultipleChoiceQuestion.showResults();//*/
   }

}

// To reflect the output I comment previous code

-----------------------------------------------------  MultipleChoiceQuestion.java : no changes in this class

import javax.swing.JOptionPane;
public class MultipleChoiceQuestion extends Question{
     
   public 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.toUpperCase();

   }

   public String ask() {

   return JOptionPane.showInputDialog(question);

   }

     
}

-----------------------------------   TrueFalseQuestion.java: as per directed in question

import javax.swing.JOptionPane;
public class TrueFalseQuestion extends Question {

   public TrueFalseQuestion(String question,String answer) {
       this.question = "TRUE or FALSE: "+ question + "\n";
       answer=answer.toUpperCase();
       if(answer=="TRUE" || answer=="T" || answer=="YES" || answer=="Y" )
       {
       correctAnswer = "TRUE";
       }
       else
       {
           correctAnswer="FALSE";
       }
          
   }
  
   @Override
   public String ask() {
       return JOptionPane.showInputDialog(question);
   }

}


Related Solutions

Your task is to modify the program from the Java Arrays programming assignment to use text...
Your task is to modify the program from the Java Arrays programming assignment to use text files for input and output. I suggest you save acopy of the original before modifying the software. Your modified program should: contain a for loop to read the five test score into the array from a text data file. You will need to create and save a data file for the program to use. It should have one test score on each line of...
You are to modify your payroll program from the last assignment to take the new copy...
You are to modify your payroll program from the last assignment to take the new copy of the payroll file called DeweyCheatemAndHow.txt which has the fields separated by a comma to use as input to your program and produce a file that lists all the salaried employee and their gross pay, then each hourly employee and their gross pay and finally each piece rate employee and their gross pay . You are to process all the entries provided in the...
CS 206 Visual Programming, Netbeans Understand and modify the attached GCDMethod.java so it can find the...
CS 206 Visual Programming, Netbeans Understand and modify the attached GCDMethod.java so it can find the greatest common divisor of three numbers input by the user.  Hints: modify the gcd() method by adding the third parameter. import java.util.Scanner; public class GCDMethod { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter first integer: "); int n1 = input.nextInt(); System.out.print("Enter second integer: ");...
Java Programming For this assignment, you should modify only the User.java file. Make sure that the...
Java Programming For this assignment, you should modify only the User.java file. Make sure that the InsufficientFundsException.java file is in the same folder as your User.java File. To test this program you will need to create your own "main" function which can import the User, create an instance and call its methods. One of the methods will throw an exception in a particular circumstance. This is a good reference for how throwing exceptions works in java. I would encourage you...
This programming assignment will consist of a C++ program. Your program must compile correctly and produce...
This programming assignment will consist of a C++ program. Your program must compile correctly and produce the specified output. Please note that your programs should comply with the commenting and formatting described in the Required Program Development Best Practices document that has been discussed in class and is posted to the eLearning system. Please see this descriptive file on the eLearning system for more details. The name to use in the main configuration screen text box Name: [ ] in...
CS 400 Assignment 5 Recursive/Backtracking: Generating Permutations WRITE CODE IN C++ PROGRAMMING LANGUAGE WITH COMMENTS INCLUDED...
CS 400 Assignment 5 Recursive/Backtracking: Generating Permutations WRITE CODE IN C++ PROGRAMMING LANGUAGE WITH COMMENTS INCLUDED Description: Mimic the code for N-queen problem (https://introcs.cs.princeton.edu/java/23recursion/Queens.java.html), develop a program that generates all permutations for the set {1, 2, 3, 4, 5}. The output should contain all 5! = 120 permutations. Output Sample: P#1: 1 2 3 4 5 P#2: 1 2 3 5 4 P#3: 1 2 4 3 5 ... P#120: 5 4 3 2 1 Hint: - Thoroughly study the...
Programming Assignment No. 5 Write a program that asks the user to enter a positive odd...
Programming Assignment No. 5 Write a program that asks the user to enter a positive odd number less than 20. If the number is 5, 11 or 15, draw a square whose width is the same as the number entered, if 3, 9, or 17, draw a box (a box is a hollowed out square) with the width the same as the number entered, otherwise just present an message saying "To be determined". Write a method for the square that...
For this assignment, write a program that will calculate the quiz average for a student in...
For this assignment, write a program that will calculate the quiz average for a student in the CSCI 240 course. The student's quiz information will be needed for later processing, so it will be stored in an array. For the assignment, declare one array that will hold a maximum of 12 integer elements (ie. the quiz scores). It is recommended that this program be written in two versions. The first version of the program will read a set of quiz...
For this assignment, write a program that will calculate the quiz average for a student in...
For this assignment, write a program that will calculate the quiz average for a student in the CSCI 240 course. The student's quiz information will be needed for later processing, so it will be stored in an array. For the assignment, declare one array that will hold a maximum of 12 integer elements (ie. the quiz scores). It is recommended that this program be written in two versions. The first version of the program will read a set of quiz...
Assignment 1 – Writing a Linux Utility Program Instructions For this programming assignment you are going...
Assignment 1 – Writing a Linux Utility Program Instructions For this programming assignment you are going to implement a simple C version of the UNIX cat program called lolcat. The cat program allows you to display the contents of one or more text files. The lolcat program will only display one file. The correct usage of your program should be to execute it on the command line with a single command line argument consisting of the name you want to...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT