Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Obtaining the digits of a integer.

Ben Jass
Ranch Hand
Posts: 98
Let's say someone inputs the number

private int number = 5321;

How could I get every single digit in that number and assign it to an int, or put it into a simple array?

private int[] numbers = {5, 3, 2, 1};

Thanks.

Bear Bibeault
Author and ninkuma
Marshal
Posts: 65225
95
You forgot to post your code. What part is giving you a problem?

Ben Jass
Ranch Hand
Posts: 98
I haven't made any code yet, that's what I'm asking you guys about. I just want to know how to take every single digit out of an integer.

Luigi Plinge
Ranch Hand
Posts: 441
You can either do it the "cheating" way by converting into a String, looping through and using Character.numericValue(s.charAt(n)), or do it a better way by repeatedly dividing by 10 and looking at the result modulus 10.

Ben Jass
Ranch Hand
Posts: 98
Luigi, I appreciate your help a lot, do you think you could give a little more of an example for the second option? Like give some code? I'm sorry, I'm just having some trouble following.

Bear Bibeault
Author and ninkuma
Marshal
Posts: 65225
95
Ben Jass wrote:Like give some code?

You should know by now that that's not how things work here. Please read: NotACodeMill. Are you saying you can't even get started at all? You've already been give two algorithms. Give one of them a try!

Ben Jass
Ranch Hand
Posts: 98

Bear Bibeault
Author and ninkuma
Marshal
Posts: 65225
95
Not a bad start, but think about the hard-coded 5. What if the number is in the millions?

Ben Jass
Ranch Hand
Posts: 98
My program will only allow 3 digit numbers at the max, so no need. This doesn't even work as it is, it just prints out 1.

Bear Bibeault
Author and ninkuma
Marshal
Posts: 65225
95
But as a learning exercise (after all, that's why you are here, no?) write the algorithm to handle numbers of any size.

Ben Jass
Ranch Hand
Posts: 98
Ok, that's not that hard, whatever the input, convert to a string, get the length() of that string, convert back to an int and put that as the maximum amount.

That's what I'm not trying to get at though. I don't know how to separate the digits of a number.

Bear Bibeault
Author and ninkuma
Marshal
Posts: 65225
95
Hint: you are expecting a different value for every iteration of your loop. Yet, the loop changes nothing. So how could the result of each iteration change?

My advice: back away from the keyboard and solve the problem with pencil and paper mathematically before trying to write code that mirrors the solution that you come up with.

Luigi Plinge
Ranch Hand
Posts: 441
You forgot an important part of
Luigi Plinge wrote:by repeatedly dividing by 10 and looking at the result modulus 10.

And you don't have to set the number of iterations in the loop in advance...

Ben Jass
Ranch Hand
Posts: 98
Thanks luigi, I got it.