# Index of an int

Printable View

• 02-24-2010, 03:25 AM
wake
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?
• 02-24-2010, 03:34 AM
Fubarable
Quote:

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.
• 02-24-2010, 04:35 AM
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
• 02-24-2010, 05:20 AM
Fubarable
Quote:

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
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!
• 02-24-2010, 02:54 PM
wake
Thanks a ton. That seems to work nicely.