KnowledgeBoat Logo

Computer Applications

Define a class Calculate to accept two numbers as instance variables. Use the following member methods for the given purposes:

Class name — Calculate

Data members — int a, int b

Member methods:
void inputdata() — to input both the values
void calculate() — to find sum and difference
void outputdata() — to print sum and difference of both the numbers
Use a main method to call the functions.

Java

Java Classes

85 Likes

Answer

import java.util.Scanner;

public class Calculate
{
    private int a;
    private int b;
    private int sum;
    private int diff;

    public void inputdata() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter first number: ");
        a = in.nextInt();
        System.out.print("Enter second number: ");
        b = in.nextInt();
    }
    
    public void calculate() {
        sum = a + b;
        diff = a - b;
    }
    
    public void outputdata() {
        System.out.println("Sum = " + sum);
        System.out.println("Difference = " + diff);
    }
    
    public static void main(String args[]) {
        Calculate obj = new Calculate();
        obj.inputdata();
        obj.calculate();
        obj.outputdata();
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a class program to accept two numbers as instance variables. Use the following functions for the given purposes: Class Name — Calculate void inputdata() — to input both the values void calculate() — to find sum and difference void outputdata() — to print sum and difference of both the numbers Use a main method to call the functions.

Answered By

40 Likes


Related Questions