In: Computer Science
-----------------------------------------------------------------------------------------------
Create a class called MathOperations that a teacher might use to represent the basic type of mathematical operations that may be performed. The class should include the following:
Three double private variables as instance variables, number1, number2, and result.
Your class should have a default constructor that initializes the three instance variables to zero.
Your class should also have a constructor that initializes the two instance variables (number1 and number2) to the value entered by the user from keyboard.
Also provide an accessor (getter) and mutator (setter) method for each instance variable except the result, that only has an accessor method.
In addition, provide 4 methods called addNumbers(), subNumbers(), divNumbers() and mulNumbers() that calculate the relevant addition, subtraction... operations on the two numbers entered by the user and stores it in the result variable.
Create a main method and within this method create 2 objects (obj1, obj2) of the MathsOperations class that sets/initializes the two instance variables (number1 and number2) by values entered by the user from the keyboard (Hint: Use Scanner class object).
7. Call/invoke each method on these 2 objects and print the result of each operation performed (using the result getter method).
8. Note: Please make sure to check when performing a division operation that the denominator is not zero. If the denominator is zero then simply set the result to zero. (Hint: Use condition statements)
import java.util.Scanner;
class MathOperations {
private double num1;
private double num2;
private double result;
public MathOperations() {
num1=0;
num2=0;
result=0;
}
public MathOperations(double aNum1, double aNum2) {
super();
num1 = aNum1;
num2 = aNum2;
}
public double getNum1() {
return num1;
}
public double getNum2() {
return num2;
}
public double getResult() {
return result;
}
public void setNum1(double aNum1) {
num1 = aNum1;
}
public void setNum2(double aNum2) {
num2 = aNum2;
}
public void addNumbers() {
result = num1+num2;
}
public void subNumbers() {
result = num1-num2;
}
public void mulNumbers() {
result = num1*num2;
}
public void divNumbers() {
if(num2!=0)
result = num1/num2;
else
result=0;
}
}
public class TestMathOperations {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 2 numbers: ");
double d1=sc.nextDouble();
double d2=sc.nextDouble();
MathOperations m1 = new MathOperations(d1,d2);
m1.addNumbers();
System.out.println(m1.getResult());
m1.subNumbers();
System.out.println(m1.getResult());
m1.mulNumbers();
System.out.println(m1.getResult());
m1.divNumbers();
System.out.println(m1.getResult());
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me