In: Computer Science
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:
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:
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!
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 :-