# Thread: Index of an int

1. Member
Join Date
Feb 2010
Posts
3
Rep Power
0

## Index of an int

How would I access each index of an int.

I can convert it to a String and then get the index but that gives a string. How would I leave the value indexed string as an int?

2. How would I access each index of an int.

I can convert it to a String and then get the index but that gives a string. How would I leave the value indexed string as an int?
Index of an int?

Your question doesn't make much sense. Could you rephrase it? Also if you post some code that tries to do what you want, we may be able to understand it better.

3. Member
Join Date
Feb 2010
Posts
3
Rep Power
0
I'll try again.

I have a number, 12345, and want to work with each digit within the number. How could I go about adding 1+2+3+4+5?

hope that makes more sense

4. Originally Posted by wake
I'll try again.

I have a number, 12345, and want to work with each digit within the number. How could I go about adding 1+2+3+4+5?

hope that makes more sense
Thanks, that makes MUCH more sense.

You could:
A) convert it into a String (as you mentioned above), change it into a char array via the toCharArray() method and then iterate through the char array adding as you go. To convert the chars to the proper int, you could either convert them into a String and then use Integer.parseInt(theString) or do a little char math: int myInt = myChar - '0'; For example
Java Code:
```    char c = '4';
int myInt = c - '0';
System.out.println(myInt);```
Another possible solution is use integer division and mod and a while loop to extract each number and add them.

There's also a recursive solution that can easily do this, but this may be overkill (or not).

Good luck!

5. Member
Join Date
Feb 2010
Posts
3
Rep Power
0
Thanks a ton. That seems to work nicely.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•