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