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.

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

0
int x = 10382;
String[] str1 = Integer.toString(x).split("");

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

Comments

-2

Java 8 Stream API

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

Source : stackoverflow

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.