Bianca Fuller
Bianca Fuller

Reputation: 39

How do I use modulus in a while loop to get individual digits of an integer?

I'm hoping to find a way to use a while loop (not a for loop) to get the individual digits of an integer put in through command line. Right now, I have it hard coded for how to get individual digits if a four digit integer is entered, but if I enter a five digit number it obviously won't work. I'm thinking a while loop should be able to fix that but I'm not sure how...

Here is the code I have so far

Upvotes: 0

Views: 4246

Answers (2)

Shadow
Shadow

Reputation: 4016

Try this out:

int number = 567;
int[] digits = new int[String.valueOf(number).length()];
while (number > 0)
{
    digits[String.valueOf(number).length()-1] = number % 10;
    number /= 10;
}
System.out.println(Arrays.toString(digits));

Might not be the most elegant solution, but it will give you the digits in the number, in the same order as they are in the number. Example 12345 will give the array a value of [1, 2, 3, 4, 5] when it is output.

Upvotes: 0

barak manos
barak manos

Reputation: 30136

Try this:

List<Integer> digits = new ArrayList<Integer>();
while (number > 0)
{
    digits.add(number%10);
    number /= 10;
}

Upvotes: 2

Related Questions