Computer Science
Write a class template 'Calculator' with the following specifications:
class Calculator
Data members/Instance variables
int a,b,c
Member Methods:
void readdata( ) : to accept the values of a and b.
void add( ) : to add a and b and place the result in c.
void sub( ) : to subtract b from a and place the result in c. Display the result.
void mul( ) : to multiply a and b and place the result in c. Display the result.
void div( ) : to divide a by b and place the result in c. Display the result.
Write a main method to create an object of class 'Calculator' and call the member methods to enable the task.
Objects & Classes
20 Likes
Answer
import java.util.Scanner;
class Calculator {
int a;
int b;
int c;
void readdata() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
a = in.nextInt();
System.out.print("Enter b: ");
b = in.nextInt();
}
void add() {
c = a + b;
System.out.println("Addition Result = " + c);
}
void sub() {
c = a - b;
System.out.println("Subtraction Result = " + c);
}
void mul() {
c = a * b;
System.out.println("Multiplication Result = " + c);
}
void div() {
c = a / b;
System.out.println("Division Result = " + c);
}
public static void main(String args[]) {
Calculator obj = new Calculator();
obj.readdata();
obj.add();
obj.sub();
obj.mul();
obj.div();
}
}
Answered By
10 Likes
Related Questions
In what way is a class helpful in creating a user defined data type?
What do you mean by instantiating a class?
Design a class 'Time' with the following specifications:
class Time
Data members/Instance variables
int hour, min, secMember Methods:
void gettime( ) : to accept a time in hour, minute and second. void showtime( ) : to display the time in terms of hour, minute and second.Write a main method to create an object of class 'Time' and call the member methods.
Design a class 'Rectangle' with the following specifications:
class Rectangle
Data members/Instance variables
int length, breadth, area, perimeterMember methods:
void input( ) : to accept length and breadth of a rectangle.
void calculate( ) : to calculate area and perimeter of rectangle.
void display( ) : to print area and perimeter of rectangle.Write a main method to create an object of class 'Rectangle' and call the member methods.