×

Java Programs

Java Practice

java program to find sum and product of all digits of a number using class

In this program we will read a positive integer number and then calculate product of all digits using a class. For example, if input number is 12345 - sum of all digits, product of all digits will be 15 , 120.

// Java program to find sum and product of 
// all digits using class

import java.util.*;

class DigitsOpr {
  private int num;

  //function to get value of num
  public void getNum(int x) {
    num = x;
  } /*End of getNum()*/

  //function to calculate sum of all digits
  public int sumDigits() {
    int n, sum = 0;
    n = num; //keep value of num safe

    while (n > 0) {
      sum += (n % 10); //find digit using n=n%10 
      n /= 10;
    }
    return sum;
  } //End of sumDigits()

  //function to calculate product of all digits
  public int productDigits() {
    int n, pro;
    n = num; //keep value of num safe
    pro = 1;
    while (n > 0) {
      pro *= (n % 10); //find digit using n=n%10 
      n /= 10;
    }
    return pro;
  } //End of productDigits()
}

public class Main {
  public static void main(String[] s) {
    DigitsOpr dig = new DigitsOpr();
    int n;

    Scanner sc = new Scanner(System.in);

    //read number
    System.out.print("Enter an +ve integer number:");
    n = sc.nextInt();

    dig.getNum(n);
    System.out.println("SUM of all digits: " + dig.sumDigits());
    System.out.println("PRODUCT of all digits: " + dig.productDigits());

  }
}

Output

Compile: javac Main.java
Run: java Main

Output: Enter an +ve integer number:1234567 SUM of all digits: 28 PRODUCT of all digits: 5040

Java Class and Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.