Question

In: Computer Science

Java For this project, we want to build a calculator program that can perform simple calculations...

Java

For this project, we want to build a calculator program that can perform simple calculations and provide an output. If it encounters any errors, it should print a helpful error message giving the nature of the error.

You may use any combination of If-Then statements and Try-Catch statements to detect and handle errors.

Program Specification

Input

Our program should accept input in one of two ways:

  1. If a command-line argument is provided, it should read input from the file given as that argument. If it cannot open the file, it should print the error message specified below and exit.
  2. If no command-line arguments are provided, the program should read input directly from the terminal.

Correct input will consist of a single line following the format:

<number> <symbol> <number>

The numbers can be any valid number, either integer or floating point. For simplicity, our program will treat all numbers as floating point.

The symbol can be any of the following: +, -, *, / or % representing the five common mathematical operations.

State

This project does not require any internal state. However, it should store all numbers as floating point values.

Output

The calculator should output the correct result of the requested calculation, provided that it is possible to do so. Output should be presented as a floating point number.

However, if the program encounters an error when parsing the input, it should print the most appropriate of these helpful error messages:

  • Error: Unable to open file! - if the file provided as a command-line argument cannot be opened
  • Error: No input provided! - if the input is blank
  • Error: Unable to convert first operand to a number! - if the first token is not a number
  • Error: Unknown mathematical symbol! - if the second token is not a recognized symbol
  • Error: Unable to convert second operand to a number! - if the third token is not a number
  • Error: Input format is invalid or incomplete! - if there are not exactly three tokens separated by spaces
  • Error: Division or modulo by 0! - if the second operand is 0 and the symbol is either % or /

Sample Input and Output

Input 1

8 + 5

Output 1

13.0

Input 2

3 / 0

Output 2

Error: Division or modulo by 0!

Input 3

5.0 +- 3

Output 3

Error: Unknown mathematical symbol! 

Input 4

18.125+3

Output 4

Error: Input format is invalid or incomplete!

Input 5

42.5 * 12.34.5

Output 5

Error: Unable to convert second operand to a number!

Solutions

Expert Solution

Calculator.java :-

import java.io.*;
import java.util.*;

public class Calculator
{
    // Program entry point 
        public static void main(String[] args) {
            /*
            Check if one command line argument is passed or not if yes then
            call handleFileInput() method to handle input from file.
            */
                if(args.length == 1) {
                    handleFileInput(args[0]);
                }
                
                /*
                if no command line argument is passed then
                call handleConsoleInput() to handle input from console.
                */
                else {
                    handleConsoleInput();
                }
                
        }
        
        /*
        method to handle input from fileName.
        */
        static void handleFileInput(String fileName) {
            /*
            place all file related opration inside try block so that
            when any error (Exception) occr then catch block shw an appropriate message.
            */
            try {
                // Create File object
                File file = new File(fileName);
                // Read file
                FileReader reader =new FileReader(file); 
                // Read Buffer
                BufferedReader br=new BufferedReader(reader);
                
                // Read one line from a file and split into tokens (which are separated by space)
                // and store tokens in String array named tokens
                String line = br.readLine();
                if(line != null) {
                 String[] tokens = line.split(" ");
                 // call validateInput() method to validate input from file.
                 validateInput(tokens);
                }
                else {
                    System.out.println("Error: No input provided!");
                    return;
                }
            } 
            
            // if any Exception occur in try block the catch block excute and display an error message
            catch(IOException e) {
                System.out.println("Error: Unable to open file!");
            }
        }
        
        /*
        method to handle input from console
        */
        static void handleConsoleInput() {
            // Scanner object to get console input.
            Scanner scan = new Scanner(System.in);
            // read console line and store in String object input
            String input = scan.nextLine();
            
            // check if input is empty 
            // if input is empty show error message and return (terminate further execution)
            if(input.equals("")) {
                System.out.println("Error: No input provided!");
                return;
            }
            
            // split input String into words which are separated by space
            String[] inputArray = input.split(" ");
            // call validateInput() method to validate console input.
            validateInput(inputArray);
        }
        
        
        /*
        method to validate from both file and console.
        validateInput() accept one String array parameter,
        */
        static void validateInput(String[] inputArray)  {
            double operand1,operand2;
            String operator;
            
            // if three token are not provided the display error message as below.
            if(inputArray.length != 3) {
                System.out.println("Error: Input format is invalid or incomplete!");
                return;
            }
            
            /*
            convert first token to Double using try catch if any Exception occur then
            catch block will display an appropriate message.
            usually when first token in not a numeric value 
            
            */
            try {
                operand1 = Double.parseDouble(inputArray[0]);
            } catch(Exception e) {
                System.out.println("Error: Unable to convert first operand to a number!");
                return;
            } 
            /*
            Check if second token is one from +,-,*,/,% if then store value of second token in operator variable
            else display an error message.
            */
            if(isOperator(inputArray[1])) {
                operator = inputArray[1];
            }
            else {
                System.out.println("Error: Unknown mathematical symbol!");
                return;
            }
            
            /*
            convert third token to Double using try catch if any Exception occur then
            catch block will display an appropriate message.
            usually when third in not a numeric value 
            
            */
           try {
               operand2 = Double.parseDouble(inputArray[2]);
           } catch(Exception e) {
               System.out.println("Error: Unable to convert second operand to a number!");
                return;
           }
           
           // if all three tokens are validated successfully then
           // call performArithmetic() to perform arithmetic operartion
           // pass two operands and one operator as parameter.
            performArithmetic(operand1,operator,operand2);
            
        }
        
        /*
        method to perform arithmetic operartion
        operand1: double type value (first operand)
        operator: String type value (operator)
        operand2 : double type value (second operand)
        */
        static void performArithmetic(double operand1,String operator,double operand2) {
            // if operator is + then perform addition operation and display result on console.
            if(operator.equals("+")) {
                System.out.println(operand1+operand2);
            }
            // if operator is - then perform substraction operation and display result on console.
            else if(operator.equals("-")) {
                System.out.println(operand1 - operand2);
            }
            // if operator is * then perform multiplication operation and display result on console.
            else if(operator.equals("*")) {
                System.out.println(operand1 * operand2);
            }
            /*
            if operator is / then check if second operand is 0 or not if yes then
            display message 'Division or modulo by 0!' else perform Division opration and display result.
            
            */
            else if(operator.equals("/")) {
                if(operand2==0) {
                    System.out.println("Error: Division or modulo by 0!");
                }
                else {
                    System.out.println(operand1 / operand2);
                }
            }
            /*
            if operator is % then check if second operand is 0 or not if yes then
            display message 'Division or modulo by 0!' else perform Division opration and display result.
            
            */
            else if(operator.equals("%")) {
                if(operand2==0) {
                    System.out.println("Error: Division or modulo by 0!");
                }
                else {
                    System.out.println(operand1 % operand2);
                }
            }
        }
        
        /*
        method to check if passed string is equals to one from +,-,*,/,% if yes then
        return true otherwise false.
        input : String type input
        return : boolean value
        */
        static boolean isOperator(String input) {
            if(input.equals("+") || input.equals("-") || input.equals("*") || input.equals("/") || input.equals("%")) {
                return true;
            }
            return false;
        }
}

Sample Outputs :-

Please refer to the Screenshot of the code given below to understand indentation of the code :-


Related Solutions

Java Language Only Use Java FX In this project we will build a BMI calculator. BMI...
Java Language Only Use Java FX In this project we will build a BMI calculator. BMI is calculated using the following formulas: Measurement Units Formula and Calculation Kilograms and meters (or centimetres) Formula: weight (kg) / [height (m)]2 The formula for BMI is weight in kilograms divided by height in meters squared. If height has been measured in centimetres, divide by 100 to convert this to meters. Pounds and inches Formula: 703 x weight (lbs) / [height (in)]2 When using...
What we want the program to do: We need to write a program, in Java, that...
What we want the program to do: We need to write a program, in Java, that will let the pilot issue commands to the aircraft to get it down safely on the flight deck. The program starts by prompting (asking) the user to enter the (start) approach speed in knots. A knot is a nautical mile and is the unit used in the navy and by the navy pilots. After the user enters the approach speed, the user is then...
I want to write this program in java. Write a simple airline ticket reservation program in...
I want to write this program in java. Write a simple airline ticket reservation program in java.The program should display a menu with the following options: reserve a ticket, cancel a reservation, check whether a ticket is reserved for a particular person, and display the passengers. The information is maintained on an alphabetized linked list of names. In a simpler version of the program, assume that tickets are reserved for only one flight. In a fuller version, place no limit...
write a program to make scientific calculator in java
Problem StatementWrite a program that uses the java Math library and implement the functionality of a scientific calculator. Your program should have the following components:1. A main menu listing all the functionality of the calculator.2. Your program should use the switch structure to switch between various options of the calculator. Your Program should also have the provision to handle invalidoption selection by the user.3. Your calculator SHOULD HAVE the following functionalities. You can add any other additional features. PLEASE MAKE...
Write a program in java that can perform encryption/decryption. In the following let the alphabet A...
Write a program in java that can perform encryption/decryption. In the following let the alphabet A be A={A, a, B, b, . . ., “ ”, “.”,“’ ”}. The encoding is A→0, a→1, B→2, b→4, . . ., Z→50, z→51, “ ”→52, “.”→53 and “’”→54.
TO BE DONE IN JAvA Complete the calculator program so that it prompts the user to...
TO BE DONE IN JAvA Complete the calculator program so that it prompts the user to enter two integers and an operation and then outputs the answer. Prompt the user three times, don't expect all the inputs on one line. Possible operations are + - * / No other words or symbols should be output, just the answer. Requested files import java.util.Scanner; /** * This is a simple calculator Java program. * It can be used to calculate some simple...
write a java program of mickey mouse it can be simple with just ears face eyes...
write a java program of mickey mouse it can be simple with just ears face eyes and mouth
Suppose we want to test whether or not three means are equal. We want to perform...
Suppose we want to test whether or not three means are equal. We want to perform this test with a 2% significance level. If we perform an ANOVA test, what is the probability of the test producing accurate results (avoiding a Type I error)? Suppose we, instead, run three separate hypothesis tests (t-tests), each with 2% significance level. Mean 1 = Mean 2 Mean 1 = Mean 3 Mean 2 = Mean 3 What is the probability that all three...
Suppose we want to test whether or not three means are equal. We want to perform...
Suppose we want to test whether or not three means are equal. We want to perform this test with a 2% significance level. If we perform an ANOVA test, what is the probability of the test producing accurate results (avoiding a Type I error)? Suppose we, instead, run three separate hypothesis tests (t-tests), each with 2% significance level. Mean 1 = Mean 2 Mean 1 = Mean 3 Mean 2 = Mean 3 What is the probability that all three...
Suppose we want to test whether or not three means are equal. We want to perform...
Suppose we want to test whether or not three means are equal. We want to perform this test with a 10% significance level. If we perform an ANOVA test, what is the probability of the test producing accurate results (avoiding a Type I error)? Suppose we, instead, run three separate hypothesis tests (t-tests), each with 10% significance level. Mean 1 = Mean 2 Mean 1 = Mean 3 Mean 2 = Mean 3 What is the probability that all three...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT