Convert an integer to an array of digits
You don't need to convert int
to String
. Just use % 10
to get the last digit and then divide your int by 10 to get to the next one.
int temp = test;
ArrayList<Integer> array = new ArrayList<Integer>();
do{
array.add(temp % 10);
temp /= 10;
} while (temp > 0);
This will leave you with ArrayList containing your digits in reverse order. You can easily revert it if it's required and convert it to int[].
Use:
public static void main(String[] args)
{
int num = 1234567;
int[] digits = Integer.toString(num).chars().map(c -> c-'0').toArray();
for(int d : digits)
System.out.print(d);
}
The main idea is
Convert the int to its String value
Integer.toString(num);
Get a stream of int that represents the ASCII value of each char(~digit) composing the String version of our integer
Integer.toString(num).chars();
Convert the ASCII value of each character to its value. To get the actual int value of a character, we have to subtract the ASCII code value of the character '0' from the ASCII code of the actual character. To get all the digits of our number, this operation has to be applied on each character (corresponding to the digit) composing the string equivalent of our number which is done by applying the map function below to our IntStream.
Integer.toString(num).chars().map(c -> c-'0');
Convert the stream of int to an array of int using toArray()
Integer.toString(num).chars().map(c -> c-'0').toArray();
The immediate problem is due to you using <= temp.length()
instead of < temp.length()
. However, you can achieve this a lot more simply. Even if you use the string approach, you can use:
String temp = Integer.toString(guess);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
newGuess[i] = temp.charAt(i) - '0';
}
You need to make the same change to use < newGuess.length()
when printing out the content too - otherwise for an array of length 4 (which has valid indexes 0, 1, 2, 3) you'll try to use newGuess[4]
. The vast majority of for
loops I write use <
in the condition, rather than <=
.
Let's solve that using recursion...
ArrayList<Integer> al = new ArrayList<>();
void intToArray(int num){
if( num != 0){
int temp = num %10;
num /= 10;
intToArray(num);
al.add(temp);
}
}
Explanation:
Suppose the value of num
is 12345.
During the first call of the function, temp
holds the value 5 and a value of num
= 1234. It is again passed to the function, and now temp
holds the value 4 and the value of num
is 123... This function calls itself till the value of num
is not equal to 0.
Stack trace:
temp - 5 | num - 1234
temp - 4 | num - 123
temp - 3 | num - 12
temp - 2 | num - 1
temp - 1 | num - 0
And then it calls the add method of ArrayList and the value of temp
is added to it, so the value of list is:
ArrayList - 1
ArrayList - 1,2
ArrayList - 1,2,3
ArrayList - 1,2,3,4
ArrayList - 1,2,3,4,5