Issue
Hello fellow programmers ! I am a beginner with Java and i am looking for a method or a way maybe to store the digits of a 6 digit number entered by the user , in an int array. For example :- if the number is 675421. then i want to store the digits in an array like :-
int[] array = new int[6];
int number = 675421
array[0] = 6;
array[1] = 7;
array[2] = 5;
array[3] = 4;
array[4] = 2;
array[5] = 1;
I want to do so so that i can work with the array to maybe sort or change the order or numbers in array. Thanks!
Solution
Here you go,
String temp = Integer.toString(number);
int[] num = new int[temp.length()];
for (int i = 0; i < temp.length(); i++){
num[i] = temp.charAt(i) - '0';
}
for (int i = 0; i < temp.length(); i++) {
System.out.println(num[i]);
}
Edit, after comment
Here, First, you are converting to your number
to a string.
Then, take each char out of it(in the loop), subtract the ASCII
value of 0
from each char to get the digit [ie, ASCII
of 0
is 48
, 1
is 49
, ... ] (see ASCII
table)
Answered By - Let'sRefactor
Answer Checked By - Gilberto Lyons (JavaFixing Admin)