Program to break Integer into Digits – Java

In this tutorial, we will write a java program to break an input integer number into digits. For example if the input number is 123 then the program should display digits 1,2,3 along with their position in the output.

package com.beginnersbook;
import java.util.Scanner;
public class JavaExample 
{
    public static void main(String args[])
    {
        int num, temp, digit, count = 0;
        
        //getting the number from user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter any number:");
        num = scanner.nextInt();
        scanner.close();
        
        //making a copy of the input number
        temp = num;
        
        //counting digits in the input number
        while(num > 0)
        {
            num = num / 10;
            count++;
        }
        while(temp > 0)
        {
            digit = temp % 10;
            System.out.println("Digit at place "+count+" is: "+digit);
            temp = temp / 10;
            count--;
        }
    }
}

 

Comments (0)
Add Comment