Design a class to overload a function num_calc as follows:
a. void num_calc(int num, char ch) with one integer argument and one character argument , computes the square of integer argument if choice ch is
‘s’ otherwise find its cube.
b. void num_calc(int a,int b, char ch) with two integer arguments and one character argument if ch is ‘p’ multiply else adds the integers.
c. void num_calc(int s1, int s2) with two integer arguments, which prints whether the integers are equal or not.
Answers
Design a class to overload a function num_calc as follows:
- void num_calc(int num, char ch) with one integer argument and one character argument , computes the square of integer argument if choice ch is 's’ otherwise find its cube.
- void num_calc(int a,int b, char ch) with two integer arguments and one character argument if ch is ‘p’ multiply else adds the integers.
- void num_calc(int s1, int s2) with two integer arguments, which prints whether the integers are equal or not.
class Overload
{
void num_calc(int num, char ch)
{
if(ch=='s')
num*=num;
else
num*=num*num;
System.out.println("Result is: "+num);
}
void num_calc(int a, int b, char ch)
{
if(ch=='p')
a*=b;
else
a+=b;
System.out.println("Result is: "+a);
}
void num_calc(int s1, int s2)
{
if(s1==s2)
System.out.println("Numbers are equal.");
else
System.out.println("Numbers are not equal.");
}
public static void main(String args[])
{
Overload obj=new Overload();
obj.num_calc(5,'s'); // computes square of 5.
obj.num_calc(5,10,'p'); //find the product of 5 and 10.
obj.num_calc(5,10); //prints that both are not equal.
}
}
Result is: 25
Result is: 50
Numbers are not equal.
import java.util.Scanner;
public class KboatCalculate
{
public void calculate(int m, char ch) {
if (ch == 's') {
if (m % 7 == 0)
System.out.println("It is divisible by 7");
else
System.out.println("It is not divisible by 7");
}
else {
if (m % 10 == 7)
System.out.println("Last digit is 7");
else
System.out.println("Last digit is not 7");
}
}
public void calculate(int a, int b, char ch) {
if (ch == 'g')
System.out.println(a > b ? a : b);
else
System.out.println(a < b ? a : b);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
KboatCalculate obj = new KboatCalculate();
System.out.print("Enter a number: ");
int n1 = in.nextInt();
obj.calculate(n1, 's');
obj.calculate(n1, 't');
System.out.print("Enter first number: ");
n1 = in.nextInt();
System.out.print("Enter second number: ");
int n2 = in.nextInt();
obj.calculate(n1, n2, 'g');
obj.calculate(n1, n2, 'k');
}
}
#SPJ2