# int to array conversion

• 11-14-2009, 01:18 PM
Yfke
int to array conversion
Hi, I'm very very new to Java (just started learning about 3 days ago) and I have a problem.

My goal is to convert an int (also negative numbers need to be converted!) into an array. If the int is, for example, -38921, I would want it to be stored in an array like this: {3, 8, 9, 2, 1}.

I have come up with a solution, but somehow I feel that there must be a shorter way... I have already searched around these forums a bit, but haven't found anything. So anyway, here's (part of) my code:

Code:

```int x = 87346;                // could be any number int length = 1; // This loop determines how many numbers the int exists of: for (int i = 10; (x>=i) | (x<=-i); i *= 10) {         length ++; } // this creates a new array called "rij":                int[] rij; rij = new int[length]; // this loop looks at the last number of x, stores it in the last empty space in // "rij" and removes the last number. Then repeats the process. // (e.g. 356: it stores 6 in { _, _, 6} and converts 356 to 35.) for(int i = 1; i <= length; i++) {         int g;                for (g = 0; !(x%10 == 0); g++) {                 if(x > 0) x--;                 if(x < 0) x++;         }         rij[rij.length - i] = g;         x /= 10; }```
Is there a shorter/better way, or am I just being too optimistic :rolleyes: ? :D
• 11-14-2009, 01:48 PM
Arnold
Convert your int to a string and check it's length. With the charAt(x) method you can even check which number is on which position.
Good luck with Java!