How can I separate the digits of an int number in Java?

0 votes
If I have a number 2500, I want the output to be: 2, 5, 0, 0. How can I separate the numbers into digits?
May 3, 2018 in Java by Daisy
• 8,050 points
4,883 views

3 answers to this question.

0 votes

We can easily separate the digits of an integer number using Java.

public static void main(String[] args) {

int num=1020; // int number


while (num > 0) {

    System.out.println( num % 10);

    num = num / 10;

}

}
answered May 3, 2018 by Akrati
• 3,150 points
0 votes

You can convert a number into String and then you can use toCharArray()  or split() method to separate the number into digits.
 

String number = String.valueOf(someInt);

char[] digits1 = number.toCharArray();
// or:
String[] digits2 = number.split("(?<=.)");
answered Aug 10, 2018 by Sushmita
• 6,880 points
0 votes
import java.util.*;

public class AmstrongNumber {

public static void main(String args[])

{

int a,i,count=0;

Scanner s= new Scanner(System.in);

System.out.println("Enter a number");

a=s.nextInt();

   while (a > 0) {

i= a % 10;

System.out.println(i);

  a = a / 10;

}

   //System.out.println(a);

}

}
answered Aug 6 by anonymous

Related Questions In Java

0 votes
2 answers

What is the use of toString method in Java and how can I use it ?

Whenever you require to explore the constructor ...READ MORE

answered Aug 23, 2018 in Java by Daisy
• 8,050 points
799 views
0 votes
3 answers

How can I add new elements to an Array in Java

String[] source = new String[] { "a", ...READ MORE

answered Sep 19, 2018 in Java by Sushmita
• 6,880 points
149 views
0 votes
2 answers
0 votes
1 answer

How can I Sort an ArrayList in Java

You can sort the ArrayList in 2 ...READ MORE

answered Apr 23, 2018 in Java by sharth
• 3,350 points
75 views
0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered Aug 20 in Java by Sirajul
• 36,820 points
184 views
0 votes
1 answer

How to divide a string in two parts

String s="yourstring"; boolean flag = true; for(int i=0;i<s.length();i++) { ...READ MORE

answered Apr 13, 2018 in Java by Rishabh
• 3,540 points
51 views
0 votes
2 answers

Integer to String conversion in java

We can do this in 2 ways: String ...READ MORE

answered Jul 27, 2018 in Java by samarth295
• 2,190 points
80 views
0 votes
3 answers

String to Double conversion in java

Double temp = Double.valueOf(str); number = temp.doubleValue(); READ MORE

answered Sep 10, 2018 in Java by Sushmita
• 6,880 points
54 views
0 votes
1 answer

How to get the number of digits in an int?

You can find out the length of ...READ MORE

answered May 14, 2018 in Java by Akrati
• 3,150 points
54 views
0 votes
2 answers

How can we add leading zeros to the number in Java?

From Java 1.5 you can use the String.format method. ...READ MORE

answered Aug 26 in Java by Sirajul
• 36,820 points
365 views