Question

In: Computer Science

FlashCards with Classes and Exception Handling – Project Project Overview Create at least 2 object classes...

FlashCards with Classes and Exception Handling – Project

Project Overview

Create at least 2 object classes (Session and Problems) and one driver class and ensure the user inputs cannot cause the system to fail by using exception handling.

Overview from Project . Implement a Java program that creates math flashcards for elementary grade students. User will enter his/her name, the type (+,-, *, /), the range of the factors to be used in the problems, and the number of problems to work. The system will provide problems, evaluate user responses to the problems, score the problems, and provide statistics about the session at the end.

Functional Requirements

  • The console entry point for the user inputs is on the same line as the prompt. (new)
  • User enters name at the beginning of a session.
  • System covers four math operations – addition, subtraction, multiplication, and division – with the user choosing which of the four operations to do in the session. Only 1 type of problem can be done in each session.
    • System should accept the following characters as inputs in both upper- and lower-case: ‘A’ for addition, ‘S’ for subtraction, ‘M’ for multiplication, and ‘D’ for division. (new)
  • User enters additional session parameters from prompts – number of problems to work and the range of values desired in the problems.
  • System presents problems to the user.
    • Entry point for the user response is after the equal sign and a space (‘ = ’). (new)
  • In the ‘Division’ case, division by zero is not allowed. System provides a different factor(s) when the situation occurs. (specified but not truly new)
  • User responds to problems with an answer and the system will provide immediate feedback for each problem, ‘correct’ or ‘incorrect.’
  • System provides summary statistics for the session once all problems are completed. Specifically provide the following 3 types of finishing data (see sample output):
    • Quick Summary: number of problems, number of problems correct, score as indicated by a percentage of problems correct, and the amount of time in seconds required to complete the problems.
    • A complete, space and comma-delimited, unlabeled record of the session – user name, operation type, range of factors, date and time of the session (at end), number of problems, number of problems correct, score shown as the number of correct problems out of the total problems, and the time in seconds spent working on the problems. (new)
    • A list of the problems in the session, including user responses and an indicator of correct/incorrect (see sample output). (new)

Optional Functional Enhancement

You will notice in the Example Output below that an exit loop has been added, giving the user the option to continue with another session without having to restart the system. You may add this function to your system .

  • the exit loop must have exception handling and be unbreakable.

Technical Requirements

The system should include the following Java components:

  • Exception handling for entering the user-name. The system will handle the entry of any character or String, including multiple tokens (a token is a single character or multiple characters or a String; multiple tokens are separated by a space), on the console line.
    • There is no additional editing or exception handling since both user-names and the input type String can be of any values.
      • Hint: Use Scanner method .nextLine() rather than Scanner method .next().
  • Exception handling for entering the operation. The system will handle the entry of any character or String or multiple tokens. Unlike the entry of the user-name, the system will process only the first character of the entry.
    • Entries that are not one of “A”, “S”, “M”, or “D” will not allow the system execution to continue, but also will not cause an uncontrolled termination.
    • System will advise user that the entry was not valid and prompt for a new entry.
    • Only a valid entry will allow the system execution to continue.
      • Hint: The code for this solution was developed in class during Week 8. You may use that code. You will need to implement it into your system.

  • Exception handling for the number of problems. The system will handle the entry of any character or string or multiple tokens. The system will process only the first token. Non-integer entries and entries less-than-or-equal-to zero will not allow the system execution to continue, but also will not cause an uncontrolled termination.
    • Entries should be checked for non-integer values and for integer values that are less than 1.
    • System will advise user that the entry was not valid and prompt for a new entry.
    • Only a valid integer entry will allow the system execution to continue.
      • Hint: The code for this solution was developed in class on Oct x or y. You may use that code. You will need to implement it into your system.
  • Exception handling for range values low and high. The system will handle the entry of any character or string. Non-integer entries and entries less-than zero will not allow the system execution to continue, but also will not cause an uncontrolled termination.
    • Entries should be checked for non-integer values and for integer values that are less than 0.
    • System will advise user that the entry was not valid and prompt for a new entry.
    • Only a valid entry will allow the system execution to continue.
      • Hint: The code for the number of problems solution is very similar to what is needed here.
  • Exception handling for responses to problems. The system will handle the entry of any character or string. Non-integer entries and entries less-than zero will not allow the system execution to continue, but also will not cause an uncontrolled termination.
    • Entries should be checked for non-integer values and for integer values that are less than 0.
    • System will advise user that the entry was not valid and prompt user by presenting the problem again.
    • Only a valid integer entry will allow the system execution to continue.
      • Hint: The code for the number of problems solution is very similar to what is needed here. However, the re-presentation of the problem will require some thought.

The system should include the following Java components (most of these are new so ‘new’ is not specified for each):

  • Name of your source code main class as follows: YourName_Project1.java
  • At least 2 object classes (Session and Problems) and one driver class
  • No methods in the driver class
  • All user inputs prompted and captured in the driver class
    • No user inputs prompted and captured in the object classes
  • All data variables in the object classes have a visibility of private
  • Update and access to the data variables in the object classes accomplished via setter and getter methods (this is required because the data variables are not visible)
  • Switch statement for selecting the math operation to perform (cases) catches both upper- and lower-case characters
  • Loop to create the selected number of problems for the session
  • Use of the Random class for the creation of the problems
  • A String array used to record the problems; use a loop to display the string variables at the end of the session
  • System.currentTimeMillis() used to record the start time, end time, and calculate the duration of the session in seconds (be sure to divide milliseconds by 1000!)
    • Start time recorded immediately before the problems begin (not at the beginning of the session when user-inputs are captured)
    • End time recorded immediately after the problems for the session are completed

Use the LocalDateTime class and the DateTimeFormatter class to display date and time of session

Optional Functional Enhancement

You will notice in the Example Output below that an exit loop has been added, giving the user the option to continue with another session without having to restart the system. You may add this function to your system .

  • the exit loop must have exception handling and be unbreakable.

Example output (from the Eclipse console)

Please enter your name: Kobe bryan

What operation would you like to work - A, S, M, or D? z

Must be A, S, M, or D. Try again.

What operation would you like to work - A, S, M, or D? &

Must be A, S, M, or D. Try again.

What operation would you like to work - A, S, M, or D? 1

Must be A, S, M, or D. Try again.

What operation would you like to work - A, S, M, or D? m

Enter number of problems: 0

Invalid entry. Try again

Enter number of problems: -3

Invalid entry. Try again

Enter number of problems: z

Invalid entry. Try again

Enter number of problems: 3

Enter low value for range of factors: -2

Invalid entry. Try again

Enter low value for range of factors: z

Invalid entry. Try again

Enter low value for range of factors: 0

Enter high value for range of factors: 9

7 * 5 = a

Invalid entry. Try again

7 * 5 = 12

incorrect

9 * 3 = 27

correct

1 * 1 = -1

Invalid entry. Try again

1 * 1 = &

Invalid entry. Try again

1 * 1 = 1

correct

Summary

Kevin Short 2020-10-16-21-41-07-669 Multiplication Range: 0 - 9 #Prob:   3 Correct:   2 Score: 66 Time:   27

7 * 5 = 12 A: 35 incorrect

9 * 3 = 27 A: 27 correct

1 * 1 = 1 A: 1 correct

Would you like to try another set of problems? Y/N? n

Thank you for playing! Play again soon.

Analysis. Describe any analysis that is required for solving the problem, including a discussion of key elements and complex statements or logic of the system.

Design. Describe the major steps for solving the problem (developing the code). A high-level outline of the classes and the variables and methods in the classes is recommended.

Testing. Describe how you tested the system.

I really appreciate you if you answer with the analysis, design and testing part .Thank you

Solutions

Expert Solution

PLEASE GIVE IT A THUMBS UP, I SERIOUSLY NEED ONE, IF YOU NEED ANY MODIFICATION THEN LET ME KNOW, I WILL DO IT FOR YOU

import java.util.*;

// Defines class FlashCards
class FlashCards {
  // Scanner class object created
  Scanner sc = new Scanner(System.in);

  // Function to displays menu, accepts user choice, validates it
  // and returns the user choice
  char menu() {
    char choice;
    // Loops valid choice entered by the user
    do {
      // Displays the menu
      System.out.print(
        "\n What operation would you like to work - " + "A, S, M, or D? "
      );
      // Converts to upper case
      choice = Character.toUpperCase(sc.next().charAt(0));

      // Checks if user choice is either 'A' or 'S' or 'M' or 'D' then valid
      if (
        choice == 'A' || choice == 'S' || choice == 'M' || choice == 'D'
      ) return choice; // Returns the choice
      // Otherwise displays error message
      else System.out.print("\n Must be A, S, M, or D. Try again.");
    } while (true); // End of do - while loop
  } // End of function

  // Function receives a message
  // Accepts a number validates it and returns it
  int validNumber(String message) {
    int num;
    // Loops till valid number entered by the user
    do {
      // try block begins
      try {
        // Displays the message
        System.out.print(message);
        // Accepts a number
        String data = sc.next();
        // Converts it to integer
        num = Integer.parseInt(data);

        // Checks if number is less than or equals to 0 then
        // throws NumberFormatException
        if (num <= 0) throw new NumberFormatException();
        // Otherwise valid number
        else return num; // returns the number
      } catch (NumberFormatException ex) { // Catch block to handle NumberFormatException // End of try block
        System.out.print("\n Invalid entry. Try again");
      } // End of catch block
    } while (true); // End of do - while loop
  } // End of function

  // main method definition
  public static void main(String[] s) {
    // Local variables to store data
    String name;
    int numberOfProblems;
    int lowValue, highValue;
    int correct;
    int score;
    int computedAnswer, userAnswer;
    double computedAnswerD, userAnswerD;
    long startTime, endTime, duration;
    String summary;
    String operation;

    // Creates an object of Random class
    Random rand = new Random();
    // Creates an object of class FlashCards
    FlashCards fc = new FlashCards();

    // Loops till user choice is not 'N' or 'n'
    do {
      // Resets summary and operation type to null for each game
      summary = operation = "";
      // Resets correct answer and score to 0 for each game
      correct = score = 0;

      // Accepts name of the player
      System.out.print("\n Please enter your name: ");
      name = fc.sc.next();

      // Calls the function to accept user choice for operation
      char choice = fc.menu();

      // Calls the function to accept number of problems
      numberOfProblems = fc.validNumber("\n Enter number of problems: ");

      // Calls the function to accept lower limit
      lowValue = fc.validNumber("\n Enter low value for range of factors: ");

      // Calls the function to accept higher limit
      highValue = fc.validNumber("\n Enter high value for range of factors: ");

      // Stores the start time
      startTime = System.currentTimeMillis();

      // Loops till number of questions
      for (int c = 0; c < numberOfProblems; c++) {
        // Generates a random number for first operand between low and high value
        int operandOne =
          rand.nextInt(highValue - lowValue + lowValue) + lowValue;
        // Generates a random number for second operand between low and high value
        int operandTwo =
          rand.nextInt(highValue - lowValue + lowValue) + lowValue;

        // Checks user selected operation
        switch (choice) {
          case 'A':
            // Stores the operation type
            operation = "Addition";
            // Calculates the sum
            computedAnswer = operandOne + operandTwo;
            // Calls the function to accept user answer passes question
            // as parameter
            userAnswer =
              fc.validNumber("\n " + operandOne + " + " + operandTwo + " = ");

            // Concatenates question, user answer, computed answer
            summary +=
              operandOne +
              " + " +
              operandTwo +
              " = " +
              userAnswer +
              " A: " +
              computedAnswer;

            // Checks if computed answer and user answer is same
            if (computedAnswer == userAnswer) {
              // Increase the correct answer counter by one
              correct++;
              // Adds score
              score += 33;
              // Concatenates status of answer as correct
              summary += " correct \n ";
              System.out.print("\n Correct");
            } // End of if condition
            // Otherwise wrong answer
            else {
              // Concatenates status of answer as incorrect
              summary += " incorrect \n ";
              System.out.print("\n Inorrect");
            } // End of else
            break;
          case 'S':
            // Stores the operation type
            operation = "Subtraction";
            // Calculates the subtraction
            computedAnswer = operandOne - operandTwo;
            // Calls the function to accept user answer passes question
            // as parameter
            userAnswer =
              fc.validNumber("\n " + operandOne + " - " + operandTwo + " = ");

            // Concatenates question, user answer, computed answer
            summary +=
              operandOne +
              " - " +
              operandTwo +
              " = " +
              userAnswer +
              " A: " +
              computedAnswer;

            // Checks if computed answer and user answer is same
            if (computedAnswer == userAnswer) {
              // Increase the correct answer counter by one
              correct++;
              // Adds score
              score += 33;
              // Concatenates status of answer as correct
              summary += " correct \n ";
              System.out.print("\n Correct");
            } // End of if condition
            // Otherwise wrong answer
            else {
              // Concatenates status of answer as incorrect
              summary += " incorrect \n";
              System.out.print("\n Inorrect");
            } // End of else
            break;
          case 'M':
            // Stores the operation type
            operation = "Multiplication";
            // Calculates the product
            computedAnswer = operandOne * operandTwo;
            // Calls the function to accept user answer passes question
            // as parameter
            userAnswer =
              fc.validNumber("\n " + operandOne + " * " + operandTwo + " = ");

            // Concatenates question, user answer, computed answer
            summary +=
              operandOne +
              " * " +
              operandTwo +
              " = " +
              userAnswer +
              " A: " +
              computedAnswer;

            // Checks if computed answer and user answer is same
            if (computedAnswer == userAnswer) {
              // Increase the correct answer counter by one
              correct++;
              // Adds score
              score += 33;
              // Concatenates status of answer as correct
              summary += " correct \n ";
              System.out.print("\n Correct");
            } // End of if condition
            // Otherwise wrong answer
            else {
              // Concatenates status of answer as incorrect
              summary += " incorrect \n";
              System.out.print("\n Inorrect");
            } // End of else
            break;
          case 'D':
            // Stores the operation type
            operation = "Division";
            // Calculates the division
            computedAnswerD = operandOne / operandTwo;
            // Calls the function to accept user answer passes question
            // as parameter
            userAnswerD =
              fc.validNumber("\n " + operandOne + " / " + operandTwo + " = ");

            // Concatenates question, user answer, computed answer
            summary +=
              operandOne +
              " / " +
              operandTwo +
              " = " +
              userAnswerD +
              " A: " +
              computedAnswerD;

            // Checks if computed answer and user answer is same
            if (computedAnswerD == userAnswerD) {
              // Increase the correct answer counter by one
              correct++;
              // Adds score
              score += 33;
              // Concatenates status of answer as correct
              summary += " correct \n ";
              System.out.print("\n Correct");
            } // End of if condition
            // Otherwise wrong answer
            else {
              // Concatenates status of answer as incorrect
              summary += " incorrect \n ";
              System.out.print("\n Inorrect");
            } // End of else
            break;
        } // End of switch - case
      } // End of for loop

      // Stores the stop time
      endTime = System.currentTimeMillis();
      // Calculates time taken
      duration = (endTime - startTime) / 1000;

      // Displays summary
      System.out.print("\n Summary\n");
      System.out.print(
        " " +
        name +
        new Date() +
        " " +
        operation +
        " Range: " +
        lowValue +
        " - " +
        highValue +
        " #Prob: " +
        numberOfProblems +
        " Correct: " +
        correct +
        " Score: " +
        score +
        " Time: " +
        duration
      );
      System.out.print("\n " + summary);

      // Accepts user choice to continue or not
      System.out.print(
        "\n Would you like to try another set of problems? Y/N? "
      );
      char ch = fc.sc.next().charAt(0);

      // Converts to upper case
      ch = Character.toUpperCase(ch);
      // Checks if user choice is 'N' then come out of the loop
      if (ch == 'N') break;
    } while (true); // End of do - while loop
    System.out.print("\n Thank you for playing! Play again soon.");
  } // End of main method
} // End of class

Related Solutions

EXCEPTION HANDLING Concept Summary: 1. Exception handling 2. Class design Description Write a program that creates...
EXCEPTION HANDLING Concept Summary: 1. Exception handling 2. Class design Description Write a program that creates an exception class called ManyCharactersException, designed to be thrown when a string is discovered that has too many characters in it. Consider a program that takes in the last names of users. The driver class of the program reads the names (strings) from the user until the user enters "DONE". If a name is entered that has more than 20 characters, throw the exception....
*In Java please! EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a  ...
*In Java please! EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a   program   that   creates   an   exception   class   called   ManyCharactersException,   designed   to   be   thrown   when   a   string   is   discovered   that   has   too   many   characters   in   it. Consider   a   program   that   takes   in   the   last   names   of   users.   The   driver   class   of   the   program reads the   names   (strings) from   the   user   until   the   user   enters   "DONE".   If   a   name is   entered   that   has   more   than   20   characters,  ...
EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a   program   that   creates  ...
EXCEPTION HANDLING Concept Summary: 1. Exception   handling   2. Class   design Description Write   a   program   that   creates   an   exception   class   called   ManyCharactersException,   designed   to be thrown when a   string is discovered that has too many characters in it. Consider a   program that   takes   in the last   names   of   users.   The   driver   class   of   the   program reads the   names   (strings) from   the   user   until   the   user   enters   "DONE".   If   a   name is   entered   that   has   more   than   20   characters,   throw   the   exception.  ...
in C#, What is an exception and what are the advantages of exception handling?
in C#, What is an exception and what are the advantages of exception handling? What are the differences between the traditional error-handling methods and the object-oriented exception-handling methods and when should you use each one? Provide three to four paragraphs detailing your findings/views on these questions..provide examples with a simple code also..
write in c++ Create a program that uses EXCEPTION HANDLING to deal with an invalid input...
write in c++ Create a program that uses EXCEPTION HANDLING to deal with an invalid input entry by a user. a. Write a program that prompts a user to enter a length in feet and inches. The length values must be positive integers. b. Calculate and output the equivalent measurement in centimeters 1 inch = 2.54 centimeters c. Write the code to handle the following exceptions: If the user enters a negative number, throw and catch an error that gives...
Java GPA calculator. Apply GUI, methods, exception handling, classes, objects, inheritance etc. The program should prompt...
Java GPA calculator. Apply GUI, methods, exception handling, classes, objects, inheritance etc. The program should prompt user for input. When done it should give an option to compute another GPA or exit.
What advantages does object-oriented exception handling provide? When a program contains multiple catch blocks, how are...
What advantages does object-oriented exception handling provide? When a program contains multiple catch blocks, how are they handled? Write the statement to declare a three-by-four array of integers with the elements initialized to zero. Name the array myArray. What is the difference between volatile and nonvolatile storage in Java programming? Give examples of different storage situations. What are some of the advantages of the ArrayList class over the Arrays class? How can you use the enhanced for loop? What does...
Create a new project in BlueJ. Create two new classes in the project, with the following...
Create a new project in BlueJ. Create two new classes in the project, with the following specifications: Class name: Part Fields: id (int) description (String) price (double) onSale (boolean) 1 Constructor: takes parameters partId, partDescrip, and partPrice to initialize fields id, description, and price; sets onSale field to false. Methods: Write get-methods (getters) for all four fields. The getters should be named getId, getDescription, getPrice, and isOnSale.
*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define...
*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will enter...
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2....
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT