create a class calculator that perform addition substraction ,multiplication and division by using method Anyone can help me
Answers
Answer in Java:
import java.util.*;
class Calculator
{
double a, b, result = 0.0;
int op = 0;
void accept(int x, double y, double z)// a method with void data type
{
op = x;
a = y;
b = z;
}
void calculate()// method
{
switch(op)
{// I am writing a menu-driven program for convenience
case 1 :
result = a + b;
break;
case 2 :
result = a - b;
break;
case 3 :
result = a * b;
break;
case 4 :
result = a / b;
break;
}
}
void print()// method
{
System.out.println("Result = " + result);
}
public static void main(String args[])// main method
{
Scanner b = new Scanner(System.in);
double m,n;
int o;
System.out.println("Enter the first number");
m = b.nextDouble();
System.out.println("Enter the second number");
n = b.nextDouble();
System.out.println("Enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division");
o = b.nextInt();
Calculator obj = new Calculator();//Creating object, which is essential while creating multiple classes.
obj.accept(o, m, n);
obj.calculate();
obj.print();
}
}