Java Program to Extract Digits from a Given Number

This is a Java Program to Extract Digits from A Given Integer.

Enter any integer as input. After that we perform several operations like modulus and division to know the number of digits in given integer and then print each of the digits of the given number.

Here is the source code of the Java Program to Extract Digits from A Given Integer. 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 Extract_Digits 
  3. {
  4.     public static void main(String args[])
  5.     {
  6.         int n, m, a, i = 1, counter = 0;
  7.         Scanner s=new Scanner(System.in);
  8.         System.out.print("Enter any number:");
  9.         n = s.nextInt();
  10.         m = n;
  11.         while(n > 0)
  12.         {
  13.             n = n / 10;
  14.             counter++;
  15.         }
  16.         while(m > 0)
  17.         {
  18.             a = m % 10;
  19.             System.out.println("Digits at position "+counter+":"+a);
  20.             m = m / 10;
  21.             counter--;
  22.         }
  23.     }
  24. }

Output:

$ javac  Extract_Digits.java
$ java  Extract_Digits
 
Enter any number:5678
Digits at position 4:8
Digits at position 3:7
Digits at position 2:6
Digits at position 1:5

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.