Print digits of a number in java
In this article you can learn 2 different approaches to print digits of a number in java, Or you can say, How can we extract all the digits of a integer number ?
Here also I use my android phone ide [java N-IDE] to write code for this problem statement.
Approach:-1 "print digits of a number in java using Integer.toString()"
public class usingMethod {
public static void main(String[] args){
int num = 39015;
String Num_S = Integer.toString(num);
System.out.println("The digits of "+ num + " are: ");
for(int i = 0; i < Num_S.length(); i++)
{
System.out.print(Num_S.charAt(i) + ", ");
}
}
}
We can't iterate a integer number in loop, but if we convert the number to a string then we can easily iterate to each index by charAt() method.
By Integer.toString() method, we can convert a interger number to a string.
Now inside a loop we can easily traverse the each index of that string and simply print the digits one by one.
Output
Approach:-2 "extract all digits of a number in java using loop"
public class usingLoop {
public static void main(String[] args){
int num = 583092;
System.out.println("The digits of "+ num + " from right to left are: ");
while(num > 0)
{
int lastDigit = num % 10;
System.out.print(lastDigit + ", ");
num = num / 10;
}
}
}
But here I have manually separated the digits from the number and printed it.
I have displayed the digits from right side to left, because by using modulus operator to any number with 10, we can get the last digit.
After printing the last digit we have to remove that digit from the number, so if we divide that number with 10 (num / 10), them output will remove the last digit.
Now again apply the same modulus operator concept until the first digit of that number.
Output
Hey guys If you learn something new from the article please share with your friends.
➡️ And if you have any questions or any doubt, feel free to ask me in the comment below, I will definitely answer to your questions.