|
Re: Assign digits in an integer to separate variables
|
Posted: Sep 2, 2009 11:18 PM
|
|
> How can I assign a variable to each digit in a 4-digit > integer. For example, suppose the user enters 1234, I want > to assign a = 1, b = 2, c = 3, and d = 4.
Off the top of my head:
1) Convert the Integer into a String. String str = ""+1234;
2) Tokenize str. - jeez, not sure if you can use StringTokenizer. Else you can just use charAt and a loop going through the String.
int [] myVars = new int[str.length()];
int index = 0;
for (index = 0; index < str.length(); index++) {
myVars[index] = new Integer(""+str.charAt(index));
}
now your array has assigned myVars[0] = 1, myVars[1] = 2, etc...
I'm not sure if the first place is taken by the empty String you may have to check against that... i.e. myVars[0] might actually be "", meaning you'll have to skip it...
There is probably an easier way, anyone please?
|
|