Java Program to Take a Number and Return List of its Digits

This is a Java Program to Take a Number and Return List of its Digits.

Enter any integer number as an input. After that we count the number of digits in the given input. The given number along with length of that number is passed to the other function where by using modulus and division operation we get all the digits of the given number.

Here is the source code of the Java Program to Take a Number and Return List of its Digits. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import java.util.Scanner;
  2. public class Digits_Number 
  3. {
  4.     int[] digits(int m,int l)
  5.     {
  6.         int x[] = new int[l];
  7.         int i = 0;
  8.         while(m > 0)
  9.         {
  10.             x[i] = m % 10;
  11.             m = m / 10;
  12.             i++;
  13.         }
  14.         return x;
  15.     }
  16.     public static void main(String[] args) 
  17.     {
  18.         int counter = 0, n, m;
  19.         Scanner s = new Scanner(System.in);
  20.         System.out.print("Enter any number:");
  21.         n = s.nextInt();
  22.         m = n;
  23.         while(n > 0)
  24.         {
  25.             n =n / 10;
  26.             counter++;
  27.         }
  28.         Digits_Number obj=new Digits_Number();
  29.         int a[]=obj.digits(m, counter);
  30.         System.out.print("Digits:");
  31.         for(int i = a.length-1; i >= 0; i--)
  32.         {
  33.             System.out.print(a[i]+" ");
  34.         }
  35.     }
  36. }

Output:

$ javac Digits_Number.java
$ java Digits_Number
 
Enter any number:6789
Digits:6 7 8 9

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.