KnowledgeBoat Logo
|

Computer Applications

Design a class to overload a method Number() as follows:

(i) void Number(int num, int d) — To count and display the frequency of a digit in a number.

Example:

num = 2565685
d = 5
Frequency of digit 5 = 3

(ii) void Number(int n1) — To find and display the sum of even digits of a number.

Example:

n1 = 29865
Sum of even digits = 2 + 8 + 6 = 16

Write a main method to create an object and invoke the above methods.

Java

User Defined Methods

77 Likes

Answer

public class Overload
{
    void Number(int num, int d) {
        int f = 0;
        
        while (num != 0) {
            int x = num % 10;
            if (x == d) {
                f++;
            }
            num /= 10;
        }
        
        System.out.println("Frequency of digit " + d + " = " + f);
    }
    
    void Number(int n1) {
        int s = 0;
        
        while (n1 != 0) {
            int x = n1 % 10;
            if (x % 2 == 0) {
                s = s + x;
            }
            n1 /= 10;
        }
        
        System.out.println("Sum of even digits = " + s);
    }
    
    public static void main(String args[]) {
        Overload obj = new Overload();
        obj.Number(2565685, 5);
        obj.Number(29865);
    }
}

Output

BlueJ output of Design a class to overload a method Number() as follows: (i) void Number(int num, int d) — To count and display the frequency of a digit in a number. Example: num = 2565685 d = 5 Frequency of digit 5 = 3 (ii) void Number(int n1) — To find and display the sum of even digits of a number. Example: n1 = 29865 Sum of even digits = 2 + 8 + 6 = 16 Write a main method to create an object and invoke the above methods.

Answered By

34 Likes


Related Questions