A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

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

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now