2

I am very new to Java programming and was wondering if there is a way to convert an integer into an int array. The reason I ask is because I know it is possible to convert an integer into a String so I was hoping there was other shortcuts for me to learn as well.

An example of what I am trying to do is taking int 10382 and turning it into int array {1, 0, 3, 8, 2}

Any help or guidance will be much appreciated, thank you very much.

Ron
  • 23
  • 1
  • 1
  • 4

3 Answers3

2

You can convert entire string and then you get the toCharArray method separately characters in an array

Scanner t = new Scanner(System.in);
     int x = t.nextInt();
     char[] xd = String.valueOf(x).toCharArray();

    for (int i = 0; i < xd.length; i++) {
        System.out.println(xd[i]);
    }

Another way of doing this would be:

int test = 12345;
        int[] testArray = new int[String.valueOf(test).length()];

And then looping over it.

Dev. Joel
  • 1,127
  • 1
  • 9
  • 14
0
int x = 10382;
String[] str1 = Integer.toString(x).split("");

for(int i=0;i<str1.length;i++){
    System.out.println(str1[i]);
}
Michael Piefel
  • 18,660
  • 9
  • 81
  • 112
bhanu avinash
  • 484
  • 2
  • 16
-2

Java 8 Stream API

int[] intArray = Arrays.stream(array).mapToInt(Integer::intValue).toArray();

Source : stackoverflow

Community
  • 1
  • 1
lxnx
  • 194
  • 2
  • 17
  • 4
    How is this right? `Arrays.stream` expects an array while the op wants to convert an `integer` to an array in the first place. All he has is an integer. We dont have `Arrays.stream(int n)` method since stream only takes `T[] arrray` according to [docs](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#stream-T:A-). – theprogrammer Jan 11 '19 at 15:20