Q:

Java program to count digits of a number using class

belongs to collection: Java Class and Object Programs

0

Example:

Input:
12345

Output:
5

Input:
123

Output:
3

 

All Answers

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

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

 

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

total answers (1)

Java Class and Object Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
java program to find sum and product of all digits... >>
<< Java program to find area and perimeter of a circl...