Question

In: Computer Science

JAVA make sure file name is FirstnameLastname_02_CS1Calculator. Thank you! Overview This program implements a simple, interactive...

JAVA make sure file name is FirstnameLastname_02_CS1Calculator. Thank you!

Overview

This program implements a simple, interactive calculator.

Major topics

  • writing a program from scratch
  • multiple methods
  • testing

In this document

  • program logic & program structure (class, methods, variables)
  • input / output
  • assumptions and limitations
  • documentation & style
  • suggested schedule
  • cover letter discussion questions
  • grading, submission, and due date
  • additional notes
  • challenges
  • sample output
  • test plan

Program Logic

  • The program prompts the user to select a type of math problem (addition, subtraction, multiplication, or division), enter the two operands, then calculates and outputs the answer.
  • The program runs until the user does not want to do any more problems.
  • A final tally of problems is printed at the end.

Program Structure and Data

                                                   Calculator class

Constructor

printIntro method

calculate method

printReport method

main method

  • one class named FirstnameLastname_02_CS1Calculator
  • methods: use the method descriptions as English comments in the code, laying out each logic step to be written in Java
    • main: calls constructor, printIntro, calculate, print report
    • constructor: initializes counters to zero, instantiates and initializes a Scanner to read from the keyboard
    • printIntro method: explains program to user
    • calculate method: primary method with a loop until the user is done
      • run a while loop until the user doesn't want to do another problem
        • display operation choices
        • get user choice, echo their choice (print it back on the screen)
          • use if-elses for which operation to print
        • get operands (numbers to use in the math problem)
        • calculate and print answer
          • use if-elses to pick which math formula
        • count operation type (addition, etc.)
          • use if-elses to pick which counter to increment
        • ask if the user wants to do another problem
      • calculate total problems done (addition count + subtraction count + …)
    • printReport method
      • outputs total of each problem done and overall total problems (see sample output)
  • instance (class level) data
    • a Scanner (needs an import statement)
    • 4 ints to count the number of each problem type (addition, etc.)
    • 1 int to hold total problem count
  • local variables: as needed in each method (perhaps none in some methods)

I/O

  • interactive only (keyboard & screen), no data files
  • input
    • user
      • enters the type of problem (addition, etc.)
      • enters two numbers for each calculation
      • enters the decision whether to do more problems
    • the user may enter either uppercase or lowercase for the continuation answer and the problem type selection
    • reading numbers: all input is String type, so it must be converted to int using a parser method from the Integer class:

firstOperand = scan.nextLine();

firstNumber = Integer.parseInt(firstOperand);

  • output (see sample output later in this document)
    • directions to the user about the problem
    • prompts to choose problem type and to enter numbers
    • calculated answer to the math problem
    • summary of problem types completed

Assumptions & Limitations

  • integers only (no real numbers)
  • input numbers and answers will fit in the range of the int data type
  • division is integer division
  • binary operations only (two operands)
  • addition, subtraction, multiplication, division and exit are the only operations supported
  • perfect user: all input will be correct (y or n only; integers only for operands)
  • results are not saved
  • the user will do at least one problem

Test Plan

  • Run the following test data, divided into sessions so that total problem counts can be checked. Restart the program to run each session (set of multiple, related problems). Be sure to check that each result is correct.
  • Simple basic problems, all operations
    • test 1: 111 + 222 = 333
    • test 2: 9999 + 8888 = 18887
    • test 3: 83 / 83 = 1
    • test 4: 84 / 83 = 1
    • test 5: 83 / 84 = 0
    • test 6: 0 – 0 = 0
    • test 7: 500000 + 500001 = 10000001
    • totals
      • Addition problems: 3
      • Subtraction problems: 1
      • Multiplication problems: 0
      • Division problems: 3
      • Total problems: 7

Note: no tests for bad data since this program is guaranteed a perfect user (i.e., no bad input).

Further work / challenges For any you do, run additional test cases to check the new functionality.

  • Add the modulus (remainder) function as a fifth choice for the user. Include a counter for "mod" problems. The math symbol for mod is % (but it does not do anything related to percentage).
  • Experiment with the NumberFormat class to learn how to place commas in results larger than 999 and include that for answers before they are printed.
  • Instead of printing "The answer is", print the result in math format:

3 + 12 = 15

  • Print totals for each type only if the user did any of that type. For example, if they did not do any subtraction problems, don't print the report line listing zero subtraction problems. Use if statements to control printing or not, by looking at the counter for that problem type.

Solutions

Expert Solution

import java.util.Scanner;                //import statement to get user input class

  class Calculator{                     //Class Containing Functions forlculation
      
    void add(int a, int b){
          int ans = a+b;
          System.out.println("Answer is" +ans);         //Function providing result for addition
          
      }
         
        void sub(int a, int b){
          
          int ans = a-b;
           System.out.println("Answer is " +ans);       //Function providing result for subtraction
           
                             }
                             
       void  mul(int a, int b){
           int ans = a*b;                                 
           System.out.println("Answer is " +ans);        //Function providing result for multiplication
           
                            }
                            
       void div(int a, int b){
           int ans = a/b;
           System.out.println("Answer is " +ans);        //Function providing result for division
                            }
       
       void mod(int a, int b){
           int ans = a%b;
           System.out.println("Answer is " +ans);        //Function providing result for modulus
                            }
       
        
     
}

public class Main{                                       //Main class containing funcion calls, name of the main class can be changed
       public static void main(String []args){           //just change the main class name and save the prog by same name if user wants
               
    Calculator cal = new Calculator();                  //Creating object of calculator class 
    Scanner sc = new Scanner(System.in);                //Creating object of Scanner class for input
    int n=0;
    
do{                                                     //do-while loop to continue after one attempt
    System.out.println("Enter your choice");            // Messages for User to choose Operation
    System.out.println("Press 1 for Addition");
    System.out.println("Press 2 for Subtraction");
    System.out.println("Press 3 for Multiplication");
    System.out.println("Press 4 for Division");
    System.out.println("Press 5 for modulus");
    
    
    int choice = sc.nextInt();                         // Input for choice of user
    
    System.out.println("Enter two numbers");        
    
    int a = sc.nextInt();                              //Input for operands
    int b = sc.nextInt();
    
    
    if(choice == 1){                                  //Function calls according to user choice using objects
        cal.add(a,b);
    }
    else if(choice == 2){
        cal.sub(a,b);
    }
    else if(choice == 3){
        cal.mul(a,b);
    }
    else if(choice ==4){
        cal.div(a,b);
    }
    else if(choice == 5){
        cal.mod(a,b);
    }
    else{
       System.out.println("Invalid Choice");          //If choice entered is not present in the list
    }
    
    System.out.println("Press 0(zero) to exit and 1(one) to continue");
     n = sc.nextInt();                                // Input to choice to continue or not

  }  while(n==1);                                     //condition for the loop
             
    
  }
}

Okay so this is the code for calculator which takes user input for choices, operands and calculates the answer. I was not crystal clear about some of your lines in the question still I made what was best possible. The explaination for the code is explained in comments represented by (//) and followed by info about the particular line. You can also change class names according to your need just don't forget to save it by the name of the class which contains the main function.Thank you and All the best.


Related Solutions

Write a program that prompts the user for a file name, make sure the file exists...
Write a program that prompts the user for a file name, make sure the file exists and if it does reads through the file, count the number of times each word appears and then output the word count in a sorted order from high to low. The program should: Display a message stating its goal Prompt the user to enter a file name Check that the file can be opened and if not ask the user to try again (hint:...
Write a C++ program that implements a simple scanner for a source file given as a...
Write a C++ program that implements a simple scanner for a source file given as a command-line argument. The format of the tokens is described below. You may assume that the input is syntactically correct. Optionally, your program can build a symbol table (a hash table is a good choice), which contains an entry for each token that was found in the input. When all the input has been read, your program should produce a summary report that includes a...
Write a C++ program that implements a simple scanner for a source file given as a...
Write a C++ program that implements a simple scanner for a source file given as a command-line argument. The format of the tokens is described below. You may assume that the input is syntactically correct. Optionally, your program can build a symbol table (a hash table is a good choice), which contains an entry for each token that was found in the input. When all the input has been read, your program should produce a summary report that includes a...
Write a C++ program that implements a simple scanner for a source file given as a...
Write a C++ program that implements a simple scanner for a source file given as a command-line argument. The format of the tokens is described below. You may assume that the input is syntactically correct. Optionally, your program can build a symbol table (a hash table is a good choice), which contains an entry for each token that was found in the input. When all the input has been read, your program should produce a summary report that includes a...
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...
simple Java project// please explain every statement with reasoning. Thank you Read from a file that...
simple Java project// please explain every statement with reasoning. Thank you Read from a file that contains a paragraph of words. Put all the words in an array, put the valid words (words that have only letters) in a second array, and put the invalid words in a third array. Sort the array of valid words using Selection Sort. Create a GUI to display the arrays using a GridLayout with one row and three columns. The input file Each line...
Using java, I need to make a program that reverses a file. The program will read...
Using java, I need to make a program that reverses a file. The program will read the text file character by character, push the characters into a stack, then pop the characters into a new text file (with each character in revers order) EX: Hello World                       eyB       Bye            becomes    dlroW olleH I have the Stack and the Linked List part of this taken care of, I'm just having trouble connecting the stack and the text file together and...
Write a Java program that allows the user to specify a file name on the command...
Write a Java program that allows the user to specify a file name on the command line and prints the number of characters, words, lines, average number of words per line, and average number of characters per word in that file. If the user does not specify any file name, then prompt the user for the name.
Write a Java Program using the concept of objects and classes. Make sure you have two...
Write a Java Program using the concept of objects and classes. Make sure you have two files Employee.java and EmployeeRunner.java. Use the template below for ease. (Please provide detailed explanation) Class Employee Class Variables: Name Work hour per week Hourly payment Class Methods: - Get/Sets - generateAnnualSalary(int:Duration of employment)               annual salary = Hourly payment * Work hours per week * 50 If the employee is working for more than 5 years, 10% added bonus             -void displayAnnualSalary ( )...
In JAVA Write a brief program that writes your name to a file in text format...
In JAVA Write a brief program that writes your name to a file in text format and then reads it back. Use the PrintWriter and Scanner classes.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT