Question

In: Computer Science

----- Please solve the questions with the code below. Thank you. ----- Exercise Overview Refactor your...

----- Please solve the questions with the code below. Thank you. -----

Exercise Overview

Refactor your code to enhance the user experience and to use objects and classes.

All functional requirements in Project 1 remain, except where enhancing the system replaces specific functions.

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)

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.

----- Please solve the questions with the code below. Thank you. -----

import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;

public class Question {
  
   public static void main(String arg[]) {
       String name;
       Scanner sc = new Scanner(System.in);
       int num,max,min,count=0;
       double num1,num2;
       double ans,result;
       String str ="";
       System.out.print("Enter your name : ");
       name = sc.nextLine();
      
       System.out.println("Enter \"A\" for Addition, \"S\" for Subtraction, \"M\" for Multiplication, \"D\" for Division: M");
       System.out.print("Enter : ");
       char ch = sc.next().charAt(0); // input choice for operation
       System.out.print("Enter the number of problems you wish to work : ");
       num = sc.nextInt();
       System.out.println("What are the low and high numbers you want in your problems?");
       System.out.print("Enter the low value for your problems : ");
       min = sc.nextInt();
       System.out.print("Enter the high value for your problems : ");
       max = sc.nextInt();
       long startTime = System.nanoTime(); // start session for questions
       if(ch == 'A')
       {
           str = "Addition";
           for(int i=0;i<num;i++)
           {
               num1 = (int)(Math.random() * (max - min + 1) + min);
               num2 = (int)(Math.random() * (max - min + 1) + min);
              
               System.out.print((int)num1 +" + "+ (int)num2 +" = ");
               ans = sc.nextDouble();
               if(ans == (num1+num2))
               {
                   count++;
                   System.out.println("Correct");
               }
               else
               {
                   System.out.println("Incorrect");
               }
           }
          
       }
       else if(ch == 'S')
       {
           str = "Subtraction";
           for(int i=0;i<num;i++)
           {
               num1 = (int)(Math.random() * (max - min + 1) + min);
               num2 = (int)(Math.random() * (max - min + 1) + min);
              
               System.out.print((int)num1 +" - "+ (int)num2 +" = ");
               ans = sc.nextDouble();
               if(ans == (num1-num2))
               {
                   count++;
                   System.out.println("Correct");
               }
               else
               {
                   System.out.println("Incorrect");
               }
           }
       }
       else if(ch == 'M')
       {
           str = "Multipication";
           for(int i=0;i<num;i++)
           {
               num1 = (int)(Math.random() * (max - min + 1) + min);
               num2 = (int)(Math.random() * (max - min + 1) + min);
              
               System.out.print((int)num1 +" * "+ (int)num2 +" = ");
               ans = sc.nextDouble();
               if(ans == (num1*num2))
               {
                   count++;
                   System.out.println("Correct");
               }
               else
               {
                   System.out.println("Incorrect");
               }
           }
       }
       else if(ch == 'D')
       {
           str = "Division";
           for(int i=0;i<num;i++)
           {
               num1 = (int)(Math.random() * (max - min + 1) + min);
               num2 = (int)(Math.random() * (max - min + 1) + min);
              
               System.out.print((int)num1 +" / "+ (int)num2 +" = ");
               ans = sc.nextDouble();
              
               result = (num1/num2);
               double result1 = Math.round(result*1000.0)/1000.0;
               if(ans == result1 )
               {
                   count++;
                   System.out.println("Correct "+result1);
               }
               else
               {
                   System.out.println("Incorrect "+result1);
               }
           }
       }
       else
       {
           System.out.println("Wrong Input !");
       }
      
       long endTime = System.nanoTime(); // sessio end for question
      
       System.out.println("");
       System.out.println("Session Summary : ");
       System.out.println(num+" problems,"+count+" correct");
       double avg = (count*1.0/num*1.0)*100;
      
      
      
       long totalTime = endTime - startTime; // calculate time in nanoseconds
       long seconds = TimeUnit.NANOSECONDS.toSeconds(totalTime); // convert time nanoseconds to seconds
      
       System.out.println("Score is "+(Math.round(avg)) +", Time is : "+seconds+" seconds");
       DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); // date
       LocalDateTime now = LocalDateTime.now(); // local time
       System.out.println("Session for "+name+" was "+str+" on "+dtf.format(now));
   }
}

Solutions

Expert Solution

Code Analysis :- we need 4 operation in this problem Addition, subtraction, Multiplication and Division so we analyse that we need four methods for those operations and every method requires two variables and and one operand so we can pass those variables and operand to a method and calculate the result.

Design:- First make a class with name operatin having two private instance variables for storing the value of min and max range and four method for each operation, Each method take a scanner object which is used to take the operand from the user. Then we implement those method carefully so no compilation like syntax errror and runtime error like divide by zero is there, After this we need to work on the Driver class that is used for testing those methods.

Testing:- After implemetation of Operation class we need a Driver class that is Question class having main method to run the class. First we take the name , number of operation user want and high and low range for generating random value for operations. Then make a menu driven program using if else statement to choose the operation. When user enters his choice and high, low value, System will generate Questions for the user if user give correct answer then it count variable will increment .. so we can use this count variable as number of correct answer given by the user. At last we note the time taken by user and print All necessary information of the user like how many correct and incorrect answer he/she given, how much time he taken, how much he scored.  

/********************************Operation.java****************************/

import java.util.Scanner;

public class Operation {

   /*
   * we need those instance variable
   */
   private int min;
   private int max;

   //constructor that instantiate a Operation
   public Operation(int min, int max) {
       this.min = min;
       this.max = max;
   }

   //return min
   public int getMin() {
       return min;
   }

   //set min
   public void setMin(int min) {
       this.min = min;
   }

   //return max
   public int getMax() {
       return max;
   }

   //set max
   public void setMax(int max) {
       this.max = max;
   }


   //addition method
   public String addition(Scanner sc) {

       int num1 = (int) (Math.random() * (max - min + 1) + min);
       int num2 = (int) (Math.random() * (max - min + 1) + min);

       System.out.print((int) num1 + " + " + (int) num2 + " = ");
       double ans = sc.nextDouble();
       if (ans == (num1 + num2)) {
           return "correct";
       } else {
           return "incorrect";
       }

   }

   //subtraction method
   public String subtraction(Scanner sc) {

       int num1 = (int) (Math.random() * (max - min + 1) + min);
       int num2 = (int) (Math.random() * (max - min + 1) + min);

       System.out.print((int) num1 + " - " + (int) num2 + " = ");
       double ans = sc.nextDouble();
       if (ans == (num1 - num2)) {

           return "correct";
       } else {
           return "incorrect";
       }
   }

   public String multiplication(Scanner sc) {

       int num1 = (int) (Math.random() * (max - min + 1) + min);
       int num2 = (int) (Math.random() * (max - min + 1) + min);

       System.out.print((int) num1 + " * " + (int) num2 + " = ");
       double ans = sc.nextDouble();
       if (ans == (num1 * num2)) {

           return "correct";
       } else {
           return "incorrect";
       }
   }

   public String division(Scanner sc) {

       int num1 = (int) (Math.random() * (max - min + 1) + min);
       int num2 = (int) (Math.random() * (max - min + 1) + min);

       System.out.print((int) num1 + " / " + (int) num2 + " = ");
       if (num2 == 0) {

           System.out.println("Can't Divide!!");
       }
       double ans = sc.nextDouble();

       double result = (num1 / num2);
       double result1 = Math.round(result * 1000.0) / 1000.0;
       if (ans == result1) {

           return "correct " + result1;
       } else {
           return "incorrect " + result1;
       }

   }
}
/*****************************Question.java************************/

import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;

public class Question {

   public static void main(String arg[]) {
       String name;
       Scanner sc = new Scanner(System.in);

       int num, max, min, count = 0;
       String str = "";
       System.out.print("Enter your name : ");
       name = sc.nextLine();

       System.out.println(
               "Enter \"A\" for Addition, \"S\" for Subtraction, \"M\" for Multiplication, \"D\" for Division: M");
       System.out.print("Enter : ");
       char ch = sc.next().charAt(0); // input choice for operation
       System.out.print("Enter the number of problems you wish to work : ");
       num = sc.nextInt();
       System.out.println("What are the low and high numbers you want in your problems?");
       System.out.print("Enter the low value for your problems : ");
       min = sc.nextInt();
       System.out.print("Enter the high value for your problems : ");
       max = sc.nextInt();
       //create object of Operation class
       Operation op = new Operation(min, max);
       long startTime = System.nanoTime(); // start session for questions
       if (ch == 'A') {
           str = "Addition";
           for (int i = 0; i < num; i++) {

               String s = op.addition(sc);

               if (s.equals("correct")) {

                   count++;
                   System.out.println("Correct");
               } else {

                   System.out.println("Incorrect");
               }
           }
       } else if (ch == 'S') {
           str = "Subtraction";
           for (int i = 0; i < num; i++) {

               if (op.subtraction(sc).equals("correct")) {
                   count++;
                   System.out.println("Correct");
               } else {
                   System.out.println("Incorrect");
               }
           }
       } else if (ch == 'M') {
           str = "Multiplication";
           for (int i = 0; i < num; i++) {

               if (op.multiplication(sc).equals("correct")) {
                   count++;
                   System.out.println("Correct");
               } else {
                   System.out.println("Incorrect");
               }
           }
       } else if (ch == 'D') {
           str = "Division";
           for (int i = 0; i < num; i++) {

               String s = op.division(sc);
               if (s.split(" ")[0].equals("correct")) {
                   count++;
                   System.out.println("Correct " + s.split(" ")[1]);

               } else {
                   System.out.println("Incorrect " + s.split(" ")[1]);
               }
           }
       } else {
           System.out.println("Wrong Input !");
       }

       long endTime = System.nanoTime(); // session end for question

       System.out.println("");
       System.out.println("Session Summary : ");
       System.out.println(num + " problems," + count + " correct");
       double avg = (count * 1.0 / num * 1.0) * 100;

       long totalTime = endTime - startTime; // calculate time in nanoseconds
       long seconds = TimeUnit.NANOSECONDS.toSeconds(totalTime); // convert time nanoseconds to seconds

       System.out.println("Score is " + (Math.round(avg)) + ", Time is : " + seconds + " seconds");
       DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); // date
       LocalDateTime now = LocalDateTime.now(); // local time
       System.out.println("Session for " + name + " was " + str + " on " + dtf.format(now));
   }
}

/*********************output**********************/

Enter your name : JKS
Enter "A" for Addition, "S" for Subtraction, "M" for Multiplication, "D" for Division: M
Enter : S
Enter the number of problems you wish to work : 3
What are the low and high numbers you want in your problems?
Enter the low value for your problems : 20
Enter the high value for your problems : 40
38 - 23 = 15
Correct
35 - 34 = 1
Correct
35 - 31 = 4
Correct

Session Summary :
3 problems,3 correct
Score is 100, Time is : 12 seconds
Session for JKS was Subtraction on 2020/10/09 09:31:16

Please let me know if you have any doubt or modify the answer, Thanks :)


Related Solutions

Please solve the questions below and show your work. Thank you. The town of Utopia has...
Please solve the questions below and show your work. Thank you. The town of Utopia has three equal-size groups of people: (i) type A people consistently prefer larger public parks to smaller; type B people prefer small public parks to large public parks, and they prefer large size to medium size parks; type C people most prefer medium size to small size public parks, which they in turn prefer by a modest amount to large levels. a. Draw on a...
Please answer the below questions ( I need answers for all the below questions). Thank you...
Please answer the below questions ( I need answers for all the below questions). Thank you True or False Write true if the statement is true or false if the statement is false. _______ The heart consists mainly of muscle. _______ Blood pressure is highest in veins. _______ Atherosclerosis is the buildup of plaque inside arteries. _______ Platelets are blood cells that fight infections. _______ Peripheral gas exchange takes place in the lungs. _______ Food travels from the mouth to...
Please solve questions in C++ ASAP!! thank you (a) Write a function in C++ called readNumbers()...
Please solve questions in C++ ASAP!! thank you (a) Write a function in C++ called readNumbers() to read data into an array from a file. Function should have the following parameters: (1) a reference to an ifstream object (2) the number of rows in the file (3) a pointer to an array of integers The function returns the number of values read into the array. It stops reading if it encounters a negative number or if the number of rows...
Please answer all the questions. Thank you Use the following data to answer the questions below:...
Please answer all the questions. Thank you Use the following data to answer the questions below: Column 1 Column 2 Column 3 Y in $ C in $ 0 500 500 850 1,000 1,200 1,500 1,550 2,000 1,900 2,500 2,250 3,000 2,600 What is mpc and mps? Compute mpc and mps. Assume investment equals $ 100, government spending equals $ 75, exports equal $ 50 and imports equal $ 35. Compute the aggregate expenditure in column 3. Draw a graph...
Solve following using Program R studio. Please show code and results. Thank you. 1. Assume that...
Solve following using Program R studio. Please show code and results. Thank you. 1. Assume that ? is a random variable follows binomial probability distribution with parameters 15 and 0.25.   a. Simulate 100 binomial pseudorandom numbers from the given distribution (using set.seed(200)) and assign them to vector called binran. b. Calculate ?(? < 8) using cumulative probability function. c. Calculate ?(? = 8) using probability distribution function. d. Calculate the average of simulated data and compare it with the corresponding...
Solve following using Program R studio. Please show code and results. Thank you. 3. Assume that...
Solve following using Program R studio. Please show code and results. Thank you. 3. Assume that ? is a random variable represents lifetime of a certain type of battery which is exponentially distributed with mean 60 hours.   a. Simulate 500 pseudorandom numbers (using set.seed(10)) and assign them to a vector called expran. b. Calculate average of simulated data and compare it with corresponding theoretical value. c. Calculate probability that lifetime is less than 50 hours using cumulative probability function. d....
Please answer all the below questions. Thank you! 7. You will need to secure contracts for...
Please answer all the below questions. Thank you! 7. You will need to secure contracts for supplies or services. Describe one contract that will be necessary for your photography business and list the legal elements of this contract that makes it valid and binding. 8. How will your photography business be obligated by warranty when providing goods or services to the public? Describe how express or implied warranties may be created. 9. You may find when securing a photography business...
Please complete both questions in MASM. Explain code clearly, thank you. Please screenshot memory outputs. Symbolic...
Please complete both questions in MASM. Explain code clearly, thank you. Please screenshot memory outputs. Symbolic Text Constants Write a program that defines symbolic names for several string literals (characters between quotes). Use each symbolic name in a variable definition. Use this code to get started: ; Symbolic Text Constants Comment ! Description: Write a program that defines symbolic names for several string literals (characters between quotes). Use each symbolic name in a variable definition. ! .386 .model flat,stdcall .stack...
Please solve in Excel and show your work. Thank you. Calculate the value of Apples’ stocks...
Please solve in Excel and show your work. Thank you. Calculate the value of Apples’ stocks given These following inputs are from Yahoo finance to see how close the model will match the current mkt price. These are 2019 figures: FCF’s = 60 billion             growth= 5%               wacc = 7.5%         Treasury securities = 51 billion     debt = 92 billion            #shares= 4.6 billion Assume the growth rate listed is for the first 4 years and then FCF’s will grow at 3.5% thereafter....
Solve the below questions using your own words PLEASE!! Make sure to write by your own...
Solve the below questions using your own words PLEASE!! Make sure to write by your own words or paraphrase 1. What is the difference between Windows and Linux server 2. Give some advantages and disadvantages Windows and Linux Operating System
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT