how would I take Integer user input such that 502 and store it in the form of array ,like arr[0]=5, arr[1]=0,arr[2]=2 and access it separately.
4 Answers
You can do this by using Integer.toString() function to transform your Integer into a String and then use String.toCharArray() function that will transform your String into a char[].
public class Program {
public static void main(String[] args) {
// Declare your scanner
Scanner sc = new Scanner(System.in);
// Waits the user to input a value in the console
Integer integer = sc.nextInt();
// Close your scanner
sc.close();
// Put your string into a char array
char[] array = integer.toString().toCharArray();
// Print the result
System.out.println(Arrays.toString(array));
}
}
input : 502
output : [5, 0, 2]
Comments
You can try this:
char[] chars = String.valueOf(520).toCharArray(); // it is the cahr array
// if you want to convert it integer array you can it as below
int[] array = new int[chars.length];
for (int i = 0; i < array.length; i++) {
array[i] = chars[i];
}
System.out.println("array = " + Arrays.toString(chars));
And it is the output:
array = [5, 2, 0]
Comments
public class MyClass {
public static int[] toArray(String input) {
// 1) check if the input is a numeric input
try {
Integer.parseInt(input);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Input \"" + input + "\" is not an integer", e);
}
// 2) get the separate digit characters of the input
char[] characters = input.toCharArray();
// 3) initialize the array where we put the result
int[] result = new int[characters.length];
// 4) for every digit character
for (int i = 0; i < characters.length; i++) {
// 4.1) convert it to the represented digit as int
result[i] = characters[i] - '0';
}
return result;
}
}
1 Comment
Francesco Pitzalis
Downvoters please leave a comment about what's wrong so I can improve and/or learn something new