Java Arithmetic Operator separate the Digits in an Integer

Question

We would like to read integer number with five digits from the user

Separate the number into its individual digits

Print the digits separated from one another.

For example, if the user types in the number 42331, the program should print

4 2 3 3 1 
 AnswerCode:
                                                                                                                                                                                                                                               
 import java.util.Scanner;
                                                                                                                                                                                                                                               
 public class Main{
     public static void main(String[] args){
         Scanner input = new Scanner(System.in);
         int[] num = new int[5];
                                                                                                                                                                                                                                               
         System.out.print("Enter a 5 digit number: ");
         int x = input.nextInt();
                                                                                                                                                                                                                                               
         for(int i=4; i>=0; --i){
             num[i] = x % 10;//from   w w  w .  ja  v  a 2  s  . c  o  m
             x /= 10;
         }
                                                                                                                                                                                                                                               
         for(int i : num){
             System.out.printf("%d ", i);
         }
         System.out.println();
     }
 }



PreviousNext

Related