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?
Printable View
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?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?
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.
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
Another possible solution is use integer division and mod and a while loop to extract each number and add them.Code:char c = '4';
int myInt = c - '0';
System.out.println(myInt);
There's also a recursive solution that can easily do this, but this may be overkill (or not).
Good luck!
Thanks a ton. That seems to work nicely.