Challenge

Project

package project;

import java.io.FileWriter;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Scanner;

interface MathOperation {

double perform(double x, double y);

}

class Addition implements MathOperation {

@Override

public double perform(double x, double y) {

return x + y;

}

}

class Subtraction implements MathOperation {

@Override

public double perform(double x, double y) {

return x - y;

}

}

class Multiplication implements MathOperation {

@Override

public double perform(double x, double y) {

return x * y;

}

}

class Division implements MathOperation {

@Override

public double perform(double x, double y) {

if (y != 0) {

return x / y;

} else {

System.out.println("Cannot divide by zero.");

return Double.NaN;

}

}

}

class Power implements MathOperation {

@Override

public double perform(double x, double y) {

return Math.pow(x, y);

}

}

class SquareRoot implements MathOperation {

@Override

public double perform(double x, double y) {

if (x >= 0) {

return Math.sqrt(x);

} else {

System.out.println("Cannot calculate square root of a negative number.");

return Double.NaN;

}

}

}

class NthRoot implements MathOperation {

@Override

public double perform(double x, double y) {

if (y != 0) {

return Math.pow(x, 1 / y);

} else {

System.out.println("Cannot calculate 0th root.");

return Double.NaN;

}

}

}

class Logarithm implements MathOperation {

@Override

public double perform(double x, double y) {

if (x > 0 && y > 0 && y != 1) {

return Math.log(x) / Math.log(y);

} else {

System.out.println("To calculate log number must be greater than 0.");

return Double.NaN;

}

}

}

class NaturalLogarithm implements MathOperation {

@Override

public double perform(double x, double y) {

if (x > 0) {

return Math.log(x);

} else {

System.out.println("To calculate log number must be greater than 0.");

return Double.NaN;

}

}

}

class Sine implements MathOperation {

@Override

public double perform(double x, double y) {

return Math.sin(Math.toRadians(x));

}

}

class InverseSine implements MathOperation {

@Override

public double perform(double x, double y) {

if (x >= -1 && x <= 1) {

return Math.toDegrees(Math.asin(x));

} else {

System.out.println("Invalid input for inverse sine calculation.");

return Double.NaN;

}

}

}

class Cosine implements MathOperation {

@Override

public double perform(double x, double y) {

return Math.cos(Math.toRadians(x));

}

}

class InverseCosine implements MathOperation {

@Override

public double perform(double x, double y) {

if (x >= -1 && x <= 1) {

return Math.toDegrees(Math.acos(x));

} else {

System.out.println("Invalid input for inverse cosine calculation.");

return Double.NaN;

}

}

}

class Tangent implements MathOperation {

@Override

public double perform(double x, double y) {

return Math.tan(Math.toRadians(x));

}

}

class InverseTangent implements MathOperation {

@Override

public double perform(double x, double y) {

return Math.toDegrees(Math.atan(x));

}

}

public class ScientificCalculator {

private boolean firstRun = true;

private double memory;

private ArrayList history;

public ScientificCalculator() {

this.memory = 0;

this.history = new ArrayList<>();

}

private double calculateSIP(double monthlyInvestment, double annualInterestRate, int compoundingFrequency, double years) {

double monthlyInterestRate = (annualInterestRate / 100) / compoundingFrequency;

double totalCompoundingPeriods = compoundingFrequency * years;

return monthlyInvestment

* ((Math.pow(1 + monthlyInterestRate, totalCompoundingPeriods) - 1) / monthlyInterestRate);

}

public double performOperation(MathOperation operation, double x, double y) {

    double result = operation.perform(x, y);

    String expression = x + " " + operation.getClass().getSimpleName() + " " + (y != 0 ? y : "") + " = " + result;

    history.add(expression);

    saveHistoryToFile(expression);

        System.out.println("Result: " + result);

    return result;

}

private void clearHistoryFile() {

        try (FileWriter fileWriter = new FileWriter("F:\\CalculationsHistory.txt", false)) {

            fileWriter.write("");

            fileWriter.flush();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

private void saveHistoryToFile(String expression) {

    try (FileWriter fileWriter = new FileWriter("F:\\CalculationsHistory.txt", true)) {

    if (firstRun) {

    clearHistoryFile();

    firstRun = false;

        }

        fileWriter.write(expression + "\n");

    } catch (IOException e) {

        e.printStackTrace();

    }

}

public static void main(String[] args) {

ScientificCalculator calculator = new ScientificCalculator();

Scanner scanner = new Scanner(System.in);

while (true) {

System.out.println("\nSelect an operation:");

System.out.println("1. Addition (+)");

System.out.println("2. Subtraction (-)");

System.out.println("3. Multiplication (*)");

System.out.println("4. Division (/)");

System.out.println("5. Exponentiation (^)");

System.out.println("6. Nth Root (Nrt) ");

System.out.println("7. Logarithmic Value (log)");

System.out.println("8. Square Root (Sqrt)");

System.out.println("9. Natural Log (logn)");

System.out.println("10. Sine (sin)");

System.out.println("11. Cosine (cos)");

System.out.println("12. Tangent (tan)");

System.out.println("13. Inverse Sine (isin)");

System.out.println("14. Inverse Cosine (icos)");

System.out.println("15. Inverse Tangent (itan)");

System.out.println("16. Store (stor)");

System.out.println("17. Recall (recall)");

System.out.println("18. Decimal to Binary (d2b)");

System.out.println("19. Binary to Decimal (b2d)");

System.out.println("20. SIP calculation");

System.out.println("21. Exit");

System.out.print("Enter operation number (1-21): ");

int choice = scanner.nextInt();

double num1 = 0;

double num2 = 0;

if (choice == 21) {

System.out.println("Exiting calculator. Goodbye!");

break;

} else if (choice >= 1 && choice <= 4) {

System.out.print("Enter the first number: ");

num1 = scanner.nextDouble();

System.out.print("Enter the second number: ");

num2 = scanner.nextDouble();

}else if (choice == 5) {

System.out.print("Enter the number: ");

num1 = scanner.nextDouble();

System.out.print("Enter the exponent(power raised): ");

num2 = scanner.nextDouble();

}else if (choice == 6) {

System.out.print("Enter the radicand: ");

        num1 = scanner.nextDouble();

        System.out.print("Enter the index (N): ");

        num2 = scanner.nextDouble();

}else if (choice == 7) {

System.out.print("Enter the number: ");

num1 = scanner.nextDouble();

System.out.print("Enter the logarithm base: ");

num2 = scanner.nextDouble();

}else if (choice == 8 || choice == 9) {

System.out.print("Enter the number: ");

num1 = scanner.nextDouble();

} else if (choice >= 10 && choice <= 12) {

System.out.println("Enter the number in degree: ");

num1 = scanner.nextDouble();

} else if (choice == 13 || choice == 14) {

System.out.println("Enter the number in radian between -1 to +1: ");

num1 = scanner.nextDouble();

}else if (choice == 15) {

System.out.println("Enter the number in radian: ");

num1 = scanner.nextDouble();

}

MathOperation selectedOperation = null;

switch (choice) {

case 1:

selectedOperation = new Addition();

calculator.performOperation(selectedOperation, num1, num2);

break;

case 2:

selectedOperation = new Subtraction();

calculator.performOperation(selectedOperation, num1, num2);

break;

case 3:

selectedOperation = new Multiplication();

calculator.performOperation(selectedOperation, num1, num2);

break;

case 4:

selectedOperation = new Division();

calculator.performOperation(selectedOperation, num1, num2);

break;

case 5:

selectedOperation = new Power();

calculator.performOperation(selectedOperation, num1, num2);

break;

case 6:

selectedOperation = new NthRoot();

calculator.performOperation(selectedOperation, num1, num2);

break;

case 7:

selectedOperation = new Logarithm();

calculator.performOperation(selectedOperation, num1, num2);

break;

case 8:

selectedOperation = new SquareRoot();

calculator.performOperation(selectedOperation, num1, 0);

break;

case 9:

selectedOperation = new NaturalLogarithm();

calculator.performOperation(selectedOperation, num1, 0);

break;

case 10:

selectedOperation = new Sine();

calculator.performOperation(selectedOperation, num1, 0);

break;

case 11:

selectedOperation = new Cosine();

calculator.performOperation(selectedOperation, num1, 0);

break;

case 12:

selectedOperation = new Tangent();

calculator.performOperation(selectedOperation, num1, 0);

break;

case 13:

selectedOperation = new InverseSine();

calculator.performOperation(selectedOperation, num1, 0);

break;

case 14:

selectedOperation = new InverseCosine();

calculator.performOperation(selectedOperation, num1, 0);

break;

case 15:

selectedOperation = new InverseTangent();

calculator.performOperation(selectedOperation, num1, 0);

break;

case 16:

System.out.print("Enter the value: ");

double storValue = scanner.nextDouble();

calculator.memory = storValue;

System.out.print("Stored value: "+ storValue);

calculator.saveHistoryToFile("Stored value: "+ storValue);

break;

case 17:

double recallResult = calculator.memory;

System.out.println("Memory Recall: " + recallResult);

calculator.saveHistoryToFile("Recalled memory: " + recallResult);

break;

case 18:

System.out.print("Enter the decimal value: ");

int d2bValue = scanner.nextInt();

String binaryResult = Integer.toBinaryString(d2bValue);

System.out.println("Binary representation: " + binaryResult);

calculator.saveHistoryToFile(

"Decimal number: "+d2bValue+

"\nBinary representation: " + binaryResult);

break;

case 19:

System.out.print("Enter the binary value: ");

String b2dValue = scanner.next();

int decimalResult = Integer.parseInt(b2dValue, 2);

System.out.println("Decimal representation: " + decimalResult);

calculator.saveHistoryToFile(

"Binary number: " + b2dValue+

"\nDecimal representation: " + decimalResult);

break;

case 20:

System.out.print("Enter the amount which you want to invest: ");

double monthlyInvestment = scanner.nextDouble();

System.out.print("Enter annual interest rate for your investment: ");

double annualInterestRate = scanner.nextDouble();

System.out.print("Enter the number of years you want to invest: ");

double years = scanner.nextDouble();

System.out.print("Enter compounding frequency (e.g., 2 for half, 4 for quarter, 12 for monthly): ");

int compoundingFrequency = scanner.nextInt();

double sipResult = calculator.calculateSIP(monthlyInvestment, annualInterestRate, compoundingFrequency, years);

System.out.println("SIP Calculation Result: " + sipResult);

calculator.saveHistoryToFile(

"Invested amount: "+ monthlyInvestment+

"\nInterest rate: "+ annualInterestRate+

"\nNumber of years: "+ years+

"\nCompounding frequency: "+ compoundingFrequency+

"\nSIP Calculation Result: " + sipResult);

break;

default:

System.out.println("Invalid operation number. Please try again.");

continue;

}

}

}

}

Report

1.Encapsulation:

a. The 'ScientificCalculator' class encapsulates the functionality related to scientific calculations, memory management, and history tracking.

b. Private variables such as 'memory', 'firstRun', and 'history' are encapsulated within the class, limiting access and providing control over their usage.

2.Abstraction:

a. The use of interfaces ('MathOperation') abstracts away the specific details of each mathematical operation, allowing for a clean and consistent interface for different operations.

b. Methods like 'performOperation' and 'calculateSIP' abstract the underlying implementation details, providing a higher-level interface for the calculator's functionality.

3.Inheritance:

a. The use of classes like 'Addition', 'Subtraction', etc., demonstrates inheritance. These classes inherit from the 'MathOperation' interface, ensuring a common contract for all mathematical operations.

b. The 'ScientificCalculator' itself does not explicitly demonstrate inheritance, but it does benefit from the inheritance of behavior through the implemented interfaces and reused code.

4.Polymorphism:

a. Polymorphism is evident in the 'performOperation' method, where different types of MathOperation objects can be passed, and the appropriate 'perform' method is dynamically called based on the actual type.

b. The use of different operation classes for various mathematical operations showcases polymorphism, allowing flexibility and extensibility in the future by adding new operations without modifying existing code.

5.Java Library:

a. The 'ScientificCalculator' class has associations with various mathematical operation classes through the 'MathOperation' interface. It uses these associations to perform different calculations based on user input.

b. The history ArrayList is associated with the ScientificCalculator to maintain a record of calculations.

6.File Handling:

a. The 'ScientificCalculator' class uses data structure by having an instance variable of type 'ArrayList' for storing the calculation history.

b. File Handling is also demonstrated in the use of file writing functionalities for history storage.

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.