So if I for example have a large number, say 18750409. I would like to divide this number into separate digits to 1,8,7,5,0,4,0,9. But I don't want to print them out right away, I would like to store them somewhere, like a number A for 1, number B for 8. (In an array possibly?) So I can do more things with these numbers later in the program before printing out results.
Any help is appreciated!
1) Get the length (# of digits) of your number (can be done by converting the number to a string and getting the length by calling .length();
int number = ...;
String my_string = "" + number;
int numberLength = my_string.length();
2) Use a for loop to cycle through your string, and make a separate array of characters and as you go through each char of your string using charAt(), store them in that array:
char[] charArray;
charArray = new char[numberLength];
for(int i = 0; i < (numberLength - 1); i++) // -> Remember, -1 because arrays start at 0!
{
charArray[i] = my_string.charAt(i);
}
Now you have an array of the digits in char form. To convert them back into ints, just cycle through that array and convert the char back to a number. Note: you can also store the digits as strings.
If you are using chars, to convert to int: use getNumericValue() -> this technically returns unicode numerical value, but unicode of a digit is that digit.
int[] digitArray;
digitArray = new int[numberLength];
for (int i =0; i< numberLength; i++)
{
digitArray[i] = charArray[i].getNumericValue();
}
And thats it. :) (Sorry if some of the java syntax is off; I have not done java in quite some time.