ADVERTISEMENT
ADVERTISEMENT

Java program to count digits of a number using class

In this program, we will read a positive integer number and find the count of all digits using a class. For example, if the input number is 12345 - the count of all digits will be 5.

Example:

Input:
12345

Output:
5

Input:
123

Output:
3

Program:

// Java program to count total number of 
// 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 count total digits
  public int countDigits() {
    int n, count;
    n = num; //keep value of num safe
    count = 0; //reset counter 
    while (n > 0) {
      n /= 10;
      count++;
    }
    return count;
  } //End of countDigits()
}

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

    Scanner sc = new Scanner(System.in);

    //read number
    System.out.print("Enter a positive integer number: ");
    n = sc.nextInt();

    dig.getNum(n);
    System.out.println("Total number of digits are: " + dig.countDigits());

  }
}

Output:

Enter a positive integer number: 12345
Total number of digits are: 5

Java Class and Object Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.