Project
\\\\ PROJECT \\\\
The Calculator Application
understanding the calculator
The Calculator application performs both basic and scientific operations. The application provides user an option to choose between the basic mode and scientific mode. Based on the option selected by the user, the application calls the corresponding class and the user can perform various mathematical operations provided in the class. There is a base class in the application which contains all the methods for calculation, basic as well as scientific. The application validates the user input also and provides appropriate messages when wrong input is given by the user.
calculator uses following methods:
|
Method |
Description |
|
Calculate() |
Default constructor for the class without any arguments. |
|
Calculate(Double dblNum, char cOperator) |
Constructor containing two arguments. This constructor is used for scientific calculations. |
|
Calculate(int iFirstNum, char cOperator, int iSecondNum) |
Constructor containing three arguments. This constructor is used for basic calculations. |
|
doCalculation() |
Calculates the result based on the numbers and operator inputted by the user. Overriding the doCalculation function.of iCalc interface. |
|
getResult() |
Prints the result of calculation. Overriding the getResult function.of iCalc interface. |
|
checkSecondNum() |
In case of division of two numbers, it checks for value 0 in the second number entered. |
|
checkInt() |
Checks if basic calculation is performed. |
|
checkDouble() |
Checks if scientific calculation is performed. |
The Calculator Class
Class Calculator calculates basic operations, namely, addition, subtraction, multiplication and division of two numbers. The class provides option to user to enter first number to be calculated, then the operation to be performed and then, the second number to be used for calculation. The input is received using java class BufferedReader. Class calculator creates an object of Class Calculate, by calling its constructor by passing three arguments, First Number, Operator and Second Number. After the creation of object of Class Calculate, doCalculation() method is called followed by getResult() method, which presents the result of calculation to the user.
also uses do while loop for multiple calculation till the user does not indicate end by n.
The ScientificCalculator Class (ScientificCalculator.java)
Class Calculator performs calculation of scientific operations, namely, sine, cosine, tangent and log of a number, nth root of number, natural logarithm of the number, sip calculator, inverse functions of cos, sin and tan,nth power of number,and important binary to decimal and decimal to binary converter of the numbers. The class provides option to user to enter the operation to be performed and the number to be calculated, The input is received using java class BufferedReader. Class ScientificCalculator inherits Class Calculate to use its methods. The class passes the user entered values to Class Calculate by calling its constructor having two arguments, Operator and the Number. The class calls doCalculation() method which is followed by getResult() method, which shows the result of calculation to the user.
Class ScientificCalculator also uses a do-while loop to provide an option to the user perform multiple calculations, till the user does not indicate the end of processing by typing ‘n’.
The UseCalculator Class
Class Calculator provides two options to the user, Basic or Scientific. Based on the option entered by the user, the class creates an instance of Class Calculator for Basic operations or an instance of Class ScientificCalculator for scientific operations.
Class UseCalculator also uses a do-while loop to provide an option to the user perform multiple calculations, till the user does not indicate the end of processing by typing ‘n’.
The calculationHistory file (calculationHistory.txt)
this file saves the calculations performed by the user in previous step only.
and the program itself asks to save this if the user want to use it as a stored memory .
-------------- WORKING WITH THE CALCULATOR APP -------------------
The steps for working with the Calculator application are:
- In the command prompt, go to the parent directory of “Calculator” directory which contains the class files for Calculator application.
- Enter the following command to run the Calculator application:
java Calculator.UseCalculator
- Enter ‘b’ (for Basic operations) or ‘s’ (for scientific operations) depending on the operations to be performed.
- If ‘b’ is entered, the following input is to be entered by the user:
- First Number
- Operator
- Second Number
- The result is shown on the command prompt based on the above values.
- Enter ‘y’ to continue or ‘n’ to discontinue using the application.
- If ‘s’ is entered, the following input is to be entered by the user:
- Operator
- Number
- The result is shown on the command prompt based on the above values.
- Enter ‘y’ to continue or ‘n’ to discontinue using the application.
- if entered y then it will show memory store if you hava saved any operation for later use.
- if entered y then discontinue the program.
...CODES FOR THE CONSOLE CALCULATOR APPLICATION...
interface iCalc
/*
-- Interface iCalc represents the basic methods for the Calculate class
-- Creates Interface Structure
-- Can be used for creating any class which would do any sort of calculations
*/
//adds interface iCalc to package calculator.
public interface iCalc {
public void doCalculation();
public void getResult();
public void showHistory();
}
class calculator
/*
* -- Class Calculator Performs basic operations like Add, Substract, Multiply, Division for two numbers
*- Uses class Calculate by creating its objects and then calling its methods
*/
import java.io.*; //imports required packages
//adds class to the package
public class Calculator extends Calculate {
public void Calc() throws java.io.IOException {
boolean next;
do { //for repeated inputs
Integer iFirstNumber = new Integer(0);
Integer iSecondNumber = new Integer(0);
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter First Number: "); // get user input
System.out.flush();
try {
iFirstNumber = Integer.parseInt(buffer.readLine());
} catch (NumberFormatException e) {
System.out.println("*///*Please provide numeric values.*///*");
System.exit(0);
}
System.out.println("Please enter the Operation (Add : +, Minus : -, Product : *, Divide : /):");
System.out.flush();
String option = buffer.readLine();
System.out.println("Please enter Second Number: ");
System.out.flush();
try {
iSecondNumber = Integer.parseInt(buffer.readLine(), 10);
} catch (NumberFormatException e) {
System.out.println("*///*Please provide numeric values.*///*");
System.exit(0);
}
if (option.length() == 1) {
Calculate c = new Calculate(iFirstNumber, option.charAt(0), iSecondNumber); // // Creates Calculate
// Class Instance
// calling class methods
c.doCalculation();
c.getResult();
} else {
System.out.println("*///*Operation Not Available. Please select any of the available options.*///*");
}
// Checks if the user would like to calculate again
System.out.println("Would you like to calculate again (y/n)?");
System.out.flush();
char response = (char) buffer.read();
if ((response == 'y') || (response == 'Y')) {
next = false;
} else {
next = true;
}
} while (!next);
}
}
class calculate
/*
* -- Class Calculate has all methods for calculation as required by any Calculator classes
*-- Implements an interface iCalc
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Scanner;
//this is including class to package calculator
public class Calculate implements iCalc { // class definition
private char Operator;
private int iFNum, iSNum;
private Double dblNumber = new Double(0);
private Double dblResult = new Double(0);
private int iResult = 0;
private boolean typeDouble = false;
private boolean typeInt = false;
public Calculate() { // Defines a constructor for scientific calculations
}
public Calculate(Double dblNum, char cOperator) {
dblNumber = dblNum;
Operator = cOperator;
typeDouble = true;
}
public Calculate(int iFirstNum, char cOperator, int iSecondNum) { // Defines a constructor for basic calculations
iFNum = iFirstNum;
iSNum = iSecondNum;
Operator = cOperator;
typeInt = true;
}
public void doCalculation() { // Calculates the Result based on the operator selected by the user
File file = new File("calculationhistory.txt"); //text file to save current history
file.deleteOnExit(); //this file is just for that calculation history after this it will delete automatically
try {
FileWriter fw = new FileWriter(file); //this is saving history
BufferedWriter bw = new BufferedWriter(fw);
bw.newLine();
iResult = 0;
dblResult = 0.0;
switch (Operator) {
case '+': // case for addition
checkInt();
iResult = iFNum + iSNum;
fw.append(iFNum + "" + Operator + "" + iSNum + "=" + iResult);
fw.close();
break;
case '-': // case for substraction
checkInt();
iResult = iFNum - iSNum;
bw.newLine();
fw.append(iFNum + "" + Operator + "" + iSNum + "=" + iResult);
fw.close();
break;
case '*': // case for multiplication
checkInt();
iResult = iFNum * iSNum;
bw.newLine();
fw.write(iFNum + "" + Operator + "" + iSNum + "=" + iResult);
fw.close();
break;
case '/': // case for division
checkInt();
if (!checkSecondNum()) {
iResult = iFNum / iSNum;
bw.newLine();
fw.write(iFNum + "" + Operator + "" + iSNum + "=" + iResult);
fw.close();
break;
}
case 'S': // case for sine operator
case 's':
checkDouble();
dblResult = Math.sin(dblNumber);
fw.write("Sin" + "" + dblNumber + "" + "" + "=" + dblResult);
fw.close();
break;
case 'C': // case for cosine operator
case 'c':
checkDouble();
dblResult = Math.cos(dblNumber);
fw.write("Cos" + "" + dblNumber + "" + "" + "=" + dblResult);
fw.close();
break;
case 'T': // case for tangent operator
case 't':
checkDouble();
dblResult = Math.tan(dblNumber);
fw.write("Tan" + "" + dblNumber + "" + "" + "=" + dblResult);
fw.close();
break;
case 'L': // case for logarithmic operation
case 'l':
checkDouble();
dblResult = Math.log(dblNumber);
fw.write("Log" + "" + dblNumber + "" + "" + "=" + dblResult);
fw.close();
break;
case 'z':
case 'Z':
checkDouble();
dblResult = Math.log(dblNumber);
break;
case 'r': // case for square root
case 'R':
checkDouble();
dblResult = Math.sqrt(dblNumber);
fw.write("Sqrt" + "" + dblNumber + "" + "" + "=" + dblResult);
fw.close();
break;
case 'i':
case 'I': // case for inverse of cosine operator
checkDouble();
dblResult = Math.acos(dblNumber);
fw.write("ICos" + "" + dblNumber + "" + "" + "=" + dblResult);
fw.close();
break;
case 'j': // case for inverse of sine operator
case 'J':
checkDouble();
dblResult = Math.asin(dblNumber);
fw.write("ISin" + "" + dblNumber + "" + "" + "=" + dblResult);
fw.close();
break;
case 'k': // case for inverse of tangent operator
case 'K':
checkDouble();
dblResult = Math.atan(dblNumber);
fw.write("ITan" + "" + dblNumber + "" + "" + "=" + dblResult);
fw.close();
break;
case 'n': // case for nth power of entered number
case 'N':
Scanner sc = new Scanner(System.in);
int nrt;
System.out.println("enter the number which you want power for ");
nrt = sc.nextInt();
checkDouble();
dblResult = (double) Math.round(Math.pow(dblNumber, nrt));
fw.write(nrt + "" + "root of" + "" + dblNumber + "" + "" + "=" + dblResult);
fw.close();
break;
case 'd': // case for converting decimal number into binary string
case 'D':
Scanner sc1 = new Scanner(System.in);
int dn;
System.out.println("enter the number to convert into binary ");
dn = sc1.nextInt();
System.out.println("Binary representation of " + dn);
String qwe = Integer.toBinaryString(dn);
System.out.println(Integer.toBinaryString(dn));
fw.write("binary rep of " + "" + dn + "" + "" + "=" + qwe);
fw.close();
break;
case '1': //case for future investment calculator
Scanner sc11 = new Scanner(System.in);
System.out.print("Enter present value: ");
double p = sc11.nextInt();
System.out.print("Enter the interest rate: ");
double r = sc11.nextInt();
System.out.print("Enter the time period in years: ");
double y = sc11.nextInt();
double f = p * Math.pow((1 + r / 100), y);
System.out.print("value is: " + f);
bw.close();
break;
case 'b': //case to change binary string to decimal number
case 'B':
System.out.println("Please enter a binary string: ");
Scanner sc2 = new Scanner(System.in);
String b2d = sc2.nextLine();
System.out.println("the decimal number is " + Integer.parseInt(b2d, 2));
break;
default:
iResult = 0;
dblResult = 0.0;
System.out.println("*///*Operation Not Available. Please select any of the available options.*///*");
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//display the result of calculations as an output
public void getResult() {
if (typeInt) {
System.out.println("The result is: " + iResult);
} else if (typeDouble) {
System.out.println("The result is: " + dblResult);
}
}
//checks for zero
public boolean checkSecondNum() {
if (iSNum == 0) {
System.out.println("Zero Not allowed");
System.exit(0);
return true;
} else {
return false;
}
}
public void checkInt() { //checking if number type is integer
if (!typeInt) {
iResult = 0;
System.out.println("*///*Operation Not Available. Please select any of the available options.*///*");
System.exit(0);
}
}
public void checkDouble() { //checking if number type is float
if (!typeDouble) {
dblResult = 0.0;
System.out.println("*///*Operation Not Available. Please select any of the available options.*///*");
System.exit(0);
}
}
@Override //overriden method
public void showHistory() {
// TODO Auto-generated method stub
}
}
class ScientificCalculator
/*
* -- Class ScientificCalculator Performs scientific calculations like Sine, Cosine, Tangent and Log of a number, squareroot, nth power of number, inverse functions, conversion of decimal to binary and vise versa
*
*-- Inherits class Calculate
*-- Methods of Super class Calculate can be directly called by using the object of this Sub class ScientificCalculator
*/
import java.io.*; //imports required packages
import java.util.Scanner;
public class ScientificCalculator extends Calculate // class definition
{
char Operator;
Double dblNumber = new Double(0);
ScientificCalculator() { //ScientificCalculator
}
ScientificCalculator(double dblNumber, char Operator) {
super(dblNumber, Operator); // Calls Super Class Constructor
this.Operator = Operator;
this.dblNumber = dblNumber;
}
public void Calc() throws java.io.IOException {
boolean next;
do {
Double d = new Double(0);
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));//buffered reader to read the input from the user
// Gets User Input
System.out.println(
"Please enter the Operation (Sine-s, Cosine-c, Tangent-t, NaturalLog-z,Logarithm-l");
System.out.println( " SquareRoot-r, NthPower-n, InverseCos-i, InverseSin-j, InverseTan-k, decimaltobinary-d");
System.out.println( " binarytodecimal-b, fiv-1, ):");
System.out.flush();
String option = buffer.readLine(); //option from above is saved here
System.out.println("Please enter a Value: ");
System.out.flush();
try {
d = Double.valueOf(buffer.readLine());
} catch (NumberFormatException e) {
System.out.println("*///*Please provide numeric values.*///*");
System.exit(0);
}
if (option.length() == 1) {
// Creates Class Instance
ScientificCalculator sc = new ScientificCalculator(d, option.charAt(0));
sc.doCalculation(); // Calls Super Class Methods
sc.getResult(); // Calls Super Class Methods
} else {
System.out.println("*///*Operation Not Available. Please select any of the available options.*///*");
}
System.out.println("Would you like to calculate again (y/n)?");
System.out.println("");
System.out.println("ShowpreviousCalculation: p"); //to show the previous calculation done by user
System.out.println("");
System.out.println("Store for later use" + "(s)");
System.out.flush();
char aa = (char) buffer.read();
if ((aa == 'y') || (aa == 'Y')) {
System.out.println("your saved memo is");
File file = new File("History.txt"); //recalling facility provided with this
BufferedReader br = new BufferedReader(new FileReader(file));
String abc = br.readLine();
System.out.println(abc);
next = false;
} else if (aa == 'p') {
File file = new File("calculationHistory.txt"); //previous calculation
BufferedReader br = new BufferedReader(new FileReader(file));
String abc = br.readLine();
System.out.println(abc);
next = false;
} else if (aa == 's') { //if want to add from existing then
System.out.println("do you want to add previous one or your own?");
System.out.println("previous :::p");
System.out.println("your own:::o");
Scanner sc = new Scanner(System.in);
String mc = sc.next();
if (mc.equals("p")) {
File file = new File("calculationHistory.txt");
BufferedReader br = new BufferedReader(new FileReader(file)); //readed from the history of calculation and saved as memory history.txt
String memo1 = br.readLine();
FileWriter fw = new FileWriter("History.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(memo1);
bw.close();
System.out.println("success!!");
} else {
System.out.println("add number of your choice."); //if want to add memo of own choice
String mc2 = sc.next();
String memo2 = mc2;
FileWriter fw = new FileWriter("History.txt"); //memo saved here
BufferedWriter bw = new BufferedWriter(fw);
bw.write(memo2);
bw.close();
System.out.println("success!!");
}
next = false;
} else {
next = true;
}
} while (!next);
}
}
class UseCalculator
/*
*-- Class UseCalculator is the Main Class for the Calculator Application
*-- Provides options to the user: Basic or Scientific Calculator
*/
import java.io.*; //importing required packages
public class UseCalculator // class definition
{
public static void main(String[] args) throws java.io.IOException {
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
//// Gets User Input
// here two type calculator created
System.out.println("Select the Calculator: Basic - B or Scientific - S."); // b for basic calculations and s for
// scientific ones
System.out.flush();
String option = buffer.readLine();
if (option.length() == 1) {
if (option.equals("B") || option.equals("b")) {
Calculator c = new Calculator(); // Calls the Basic Calculator Application
c.Calc();
} else if (option.equals("S") || option.equals("s")) {
ScientificCalculator sc = new ScientificCalculator(); // Calls the scientific Calculator Application
sc.Calc();
} else {
System.out.println("*///*Please enter option 'B' or 'S'.*///*");
}
} else {
System.out.println("*///*Please enter option 'B' or 'S'.*///*");
}
}
}
(and two history files are created on thier own by the mentioned codes in the program)
The calculationHistory (calculationHistory.txt)
this is temporary file. when we start the program this file will be create on its own. After the end of the program this file will get automatically deleted. But if we want to store it as memory to recall you have to save it to recall. Then it will save in the History.txt file for temporary recalling use. You can use this value for further calculation work.
(Output of the program is uploaded in the files)
object oriented programming
definition of object oriented programming
Object-oriented programming (OOP) is a programming paradiagram based on the concept of "objects", which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures
following are examples of object oriented programming with the use of examples from above project
The following are general OOPs concepts in Java:
Example 1
Abstraction
Abstraction aims to hide complexity from the users and show them only the relevant information. For example, if you want to drive a car, you don’t need to know about its internal workings. The same is true of Java classes. You can hide internal implementation details by using abstract classes or interfaces. On the abstract level, you only need to define the method signatures (name and parameter list) and let each class implement them in their own way.
Abstraction in Java:
- Hides the underlying complexity of data
- Helps avoid repetitive code
- Presents only the signature of internal functionality
- Gives flexibility to programmers to change the implementation of the abstract behaviour
- Partial abstraction (0-100%) can be achieved with abstract classes
- Total abstraction (100%) can be achieved with interface
Abstraction in project is as follows-
abstract class Calculator{}
Example 2
Polymorphism
polymorphism refers to the ability to perform a certain action in different ways. In Java, polymorphism can take two forms: method overloading and method overriding. Method overloading happens when various methods with the same name are present in a class. When they are called they are differentiated by the number, order, and types of their parameters. Method overriding occurs when the child class overrides a method of its parent.
Polymorphism in Java:
- The same method name is used several times.
- Different methods of the same name can be called from the object.
- All Java objects can be considered polymorphic (at the minimum, they are of their own type and instances of the Object class).
- Example of static polymorphism in Java is method overloading.
- Example of dynamic polymorphism in Java is method overriding.
polymorphism in above project is as follows-
@Override
public void showHistory() {
// TODO Auto-generated method stub
public class ScientificCalculator extends Calculate
Example 3
Inheritance
Inheritance makes it possible to create a child class that inherits the fields and methods of the parent class. The child class can override the values and methods of the parent class, however it’s not necessary. It can also add new data and functionality to its parent. Parent classes are also called superclasses or base classes, while child classes are known as subclasses or derived classes as well. Java uses the extends keyword to implement the principle of inheritance in code.
Inheritance in Java:
- A class (child class) can extend another class (parent class) by inheriting its features.
- Implements the DRY (Don’t Repeat Yourself) programming principle.
- Improves code reusability.
- Multilevel inheritance is allowed in Java (a child class can have its own child class as well).
- Multiple inheritances are not allowed in Java (a class can’t extend more than one class).
Inheritance in above project is as follows-
1.
public class Calculate implements iCalc
In above one the class Cclculate is implementing the interface iCalc in package Calculator.
The implements keyword is used to implement an interface . The interface keyword is used to declare a special type of class that only contains abstract methods. To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends ).
2.
public class ScientificCalculator extends Calculate
Here the class ScientificCalculator is extending Calculate class.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
In Java, the extends keyword is used to indicate that a new class is derived from the base class using inheritance. So basically, extends keyword is used to extend the functionality of the class.
here
parent class extends child class
|________________| keyword |_________|
|ScientificCalculator | ==============>> | Calculate |
|________________| |_________|
Example 4
Association
Besides the four main principles of OOP, Java also works with three further concepts (association, aggregation, composition) you can make use of when designing your programs. Aggregation is a special form of association, while composition is a special form of aggregation.
Association simply means the act of establishing a relationship between two unrelated classes. For example, when you declare two fields of different types (e.g. Car and Bicycle) within the same class and make them interact with each other, you have performed association.
Association in Java:
- Two separate classes are associated through their objects.
- The two classes are unrelated, each can exist without the other one.
- Can be a one-to-one, one-to-many, many-to-one, or many-to-many relationship.
Association in above project is as follows-
In above project program the class Calculate and Scientific Calculator are associated with each other by the objects do calculation and getresult.
The IS-A Association is also referred to as Inheritance.
following is IS-A association type.
public void doCalculation() {
iResult = 0;
dblResult = 0.0;
}
public void getResult() {
if (typeInt) {
System.out.println("The result is: " + iResult);
}
In project we created two classes and then associated them with the help of above objects.
Example 5
Class
The class is one of the Basic concepts of OOPs which is a group of similar entities. It is only a logical component and not the physical entity. Lets understand this one of the OOPs Concepts with example, if you had a class called “Expensive Cars” it could have objects like Mercedes, BMW, Toyota, etc. Its properties(data) can be price or speed of these cars. While the methods may be performed with these cars are driving, reverse, braking etc.
example Classes in above project are as follows-
public class Calculate implements iCalc
public class ScientificCalculator extends Calculate
public class UseCalculator
public class Calculator
Example 6
Object
An object can be defined as an instance of a class, and there can be multiple instances of a class in a program. An Object is one of the Java OOPs concepts which contains both the data and the function, which operates on the data. For example - chair, bike, marker, pen, table, car, etc.
following are some objects used -
public Calculate() { // Defines a constructor for scientific calculations
}
public Calculate(Double dblNum, char cOperator) {
dblNumber = dblNum;
Operator = cOperator;
typeDouble = true;
}
public void checkInt() {
if (!typeInt) {
iResult = 0;
System.out.println("*///*Operation Not Available. Please select any of the available options.*///*");
System.exit(0);
}