Project
PROJECT
Lets understand the calculator
This calculator is both type 1.Basc 2.Scientific
A calculator is performs arithmetic operations on numbers. The simplest calculators can do only addition, subtraction, multiplication, and division.But this calculator can, trigonometric functions .
calculator uses following methods:
Method
Description
Calculate()
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.
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 firstcalc interface.
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.
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);
}
}
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.
import java.io.*; //imports required packages
import java.util.Scanner;
public class ScientificCalculator extends Calculate // class definition
{
// extending class calculate
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 { /*The throw keyword in Java is used to explicitly throw an exception from a method or
any block of code. We can throw either checked or unchecked exception.
The throw keyword is mainly used to throw custom exceptions
*
*/
boolean next; // for repeated infiniting loop
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"
+ " SquareRoot-r, NthPower-n, InverseCos-i, InverseSin-j, InverseTan-k, decimaltobinary-d"+
" 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"); // will add privious as memo
System.out.println("your own:::o"); // will add number of our own choice
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); // will write your privious value as a memo to history .txt file for further use
bw.write(memo1);
bw.close();
System.out.println("success!!"); // shown if value saved succesfully as memo otherwise will terminate
} 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); // can be saved only once and can be yoused to only saved one value(cons)
bw.write(memo2); // shows whole expresion if saved a memo withiine a scintefic calculator
// this saved value will not be added automaticaly to your calculation , the value will be only shown
// you have to type that value for furthur calculation (cons)
bw.close();
System.out.println("success!!"); // shown if value saved succesfully as memo otherwise will terminate
}
next = false;
} else {
next = true;
}
} while (!next);
}
}
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’.
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
/*
* The flush() method of PrintWriter Class in Java is used to flush the stream.
* By flushing the stream, it means to clear the stream of any element that may be or maybe not inside the stream.
* It neither accepts any parameter nor returns any value. ... Return Value: This method do not returns any value.
*/
System.out.flush();
String option = buffer.readLine();
// will read if entered character is b or s
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 { // If entered character is other than B or S then this massage prompt will be executed
System.out.println("///*Please enter option 'B' or 'S'.///*");
}
}
}
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 .
Steps requried before use of calculator====
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.
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 MemoHistory.txt file for temporary recalling use. You can use this value for further calculation work. Ypu can use this stored value once only.1 value only saved.
interface iCalc
public interface iCalc{
public void doCalculation();
public void getResult();
}
class Calculate
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':
checkDouble();
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 + "" + "nth power 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);
}
}
}
Object Oriented programming
Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function
The following are general OOPs concepts in Java:
Java is a class-based object-oriented programming (OOP) language that is built around the concept of objects. OOP concepts (OOP) intend to improve code readability and reusability by defining how to structure a Java program efficiently. The main principles of object-oriented programming are:
Java comes with specific code structures for each OOP principle. For example, the extends keyword for inheritance or getter and setter methods for encapsulation.
1..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 interfaces
2..Encapsulation in Java:
- Restricts direct access to data members (fields) of a class.
- Fields are set to private
- Each field has a getter and setter method
- Getter methods return the field
- Setter methods let us change the value of the field
3..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.
4..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).
5..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.
6..Aggregation in Java:
- One-directional association.
- Represents a HAS-A relationship between two classes.
- Only one class is dependent on the other.
7..Composition in Java:
- A restricted form of aggregation
- Represents a PART-OF relationship between two classes
- Both classes are dependent on each other
- If one class ceases to exist, the other can’t survive alone
\\END//