0% found this document useful (0 votes)
12 views2 pages

Jack Code - Calculator

The document defines a Calculator class that encapsulates functionality for basic arithmetic operations. It includes methods to input two operands and an operator, and performs calculations based on the operator provided. The class also handles division by zero and invalid operator cases.

Uploaded by

ayo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Jack Code - Calculator

The document defines a Calculator class that encapsulates functionality for basic arithmetic operations. It includes methods to input two operands and an operator, and performs calculations based on the operator provided. The class also handles division by zero and invalid operator cases.

Uploaded by

ayo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

// Create a class named Calculator to encapsulate the calculator's functionality

class Calculator {

// Declare variables to store operands and the operator


private double operand1;
private double operand2;
private char operator;

// Method to get the first operand from the user


public void getOperand1() {
System.out.println("Enter the first operand: ");
operand1 = Console.readDouble();
}

// Method to get the operator from the user


public void getOperator() {
System.out.println("Enter the operator (+, -, *, /): ");
operator = Console.readChar();
}

// Method to get the second operand from the user


public void getOperand2() {
System.out.println("Enter the second operand: ");
operand2 = Console.readDouble();
}

// Method to perform the calculation based on the selected operator


public void calculate() {
switch (operator) {
case '+':
System.out.println(operand1 + operand2);
break;
case '-':
System.out.println(operand1 - operand2);
break;
case '*':
System.out.println(operand1 * operand2);
break;
case '/':
if (operand2 != 0) {
System.out.println(operand1 / operand2);
} else {
System.out.println("Division by zero is not allowed");
}
break;
default:
System.out.println("Invalid operator");
}
}
}

// Create an instance of the Calculator class


Calculator myCalculator = new Calculator();

// Call the methods to get the operands and perform the calculation
myCalculator.getOperand1();
myCalculator.getOperator();
myCalculator.getOperand2();
myCalculator.calculate();
```

You might also like