75

I try to convert an integer to an array. For example, 1234 to int[] arr = {1,2,3,4};.

I've written a function:

public static void convertInt2Array(int guess)  {
    String temp = Integer.toString(guess);
    String temp2;
    int temp3;
    int [] newGuess = new int[temp.length()];
    for(int i=0; i<=temp.length(); i++) {
        if (i!=temp.length()) {
            temp2 = temp.substring(i, i+1);
        } else {
            temp2 = temp.substring(i);
            //System.out.println(i);
        }
        temp3 =  Integer.parseInt(temp2);
        newGuess[i] = temp3;
    }

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

But an exception is thrown:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at q4.test.convertInt2Array(test.java:28)
at q4.test.main(test.java:14)
Java Result: 1

How can I fix this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hkguile
  • 4,235
  • 17
  • 68
  • 139

24 Answers24

92

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 <=.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • your functions can't store value 0 – hkguile Nov 09 '11 at 03:52
  • 3
    @hkinterview: They can store a *single* 0, but not leading zeroes. That's a problem with your design rather than my implementation though. Either you need to specify the length in the method call, or move away from `int` as a representation - because `00001` is the same `int` value as `1`. – Jon Skeet Nov 09 '11 at 06:02
  • 2
    @JonSkeet Can you explain me why you have put `-'0'` in the line `newGuess[i] = temp.charAt(i) - '0';` – Kasun Siyambalapitiya Jun 12 '16 at 16:30
  • @KasunSiyambalapitiya: Because that's the simplest way to get from `'0', '1', '2'` etc to the integer representations of those digits. – Jon Skeet Jun 12 '16 at 16:31
  • @JonSkeet Pardon me. I still didn't got it, in the above example String `temp` will become ="1234". so when we get `temp.charAt(0)` it is `1` ,`temp.charAt(1)` it is `2` and so on. but why is that value not assign to the `int array` as `newGuess[0]=1`,`newGuess[1]=2` and so on – Kasun Siyambalapitiya Jun 12 '16 at 16:48
  • 3
    @KasunSiyambalapitiya, no, `temp.charAt(0)` isn't `1`, it's `'1'` - the *character* '1'. That has an integer value of 49, because the Unicode character 49 is the digit 1. It's important to differentiate between the *character* value and the integer value that it represents as a digit. – Jon Skeet Jun 12 '16 at 16:54
  • `newGuess[i] = Character.getNumericValue(temp.charAt(i))` can also be used in place of `newGuess[i] = temp.charAt(i) - '0'` – CoderSam Aug 16 '19 at 12:19
  • What about negative numbers this is an incomplete answer – Phil Aug 05 '20 at 16:13
  • @Phil: I'm not sure the question really makes sense for a negative number, and it doesn't look like the OP needed that (and certainly their original code didn't try to handle it). – Jon Skeet Aug 05 '20 at 16:20
64

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[].

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vladimir
  • 9,683
  • 6
  • 36
  • 57
56

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

  1. Convert the int to its String value

    Integer.toString(num);
    
  2. 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();
    
  3. 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');
    
  4. Convert the stream of int to an array of int using toArray()

     Integer.toString(num).chars().map(c -> c-'0').toArray();
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marie Diana Tran
  • 573
  • 6
  • 10
8

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ash9
  • 149
  • 1
  • 3
5

You can use:

private int[] createArrayFromNumber(int number) {
    String str = (new Integer(number)).toString();
    char[] chArr = str.toCharArray();
    int[] arr = new int[chArr.length];
    for (int i = 0; i< chArr.length; i++) {
        arr[i] = Character.getNumericValue(chArr[i]);
    }
    return arr;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
5

You can just do:

char[] digits = string.toCharArray();

And then you can evaluate the chars as integers.

For example:

char[] digits = "12345".toCharArray();
int digit = Character.getNumericValue(digits[0]);
System.out.println(digit); // Prints 1
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James Wierzba
  • 16,176
  • 14
  • 79
  • 120
4

It would be much simpler to use the String.split method:

public static void fn(int guess) {
    String[] sNums = Integer.toString(guess).split("");
    for (String s : nums) {
    ...
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
zellio
  • 31,308
  • 1
  • 42
  • 61
3

You can do something like this:

public int[] convertDigitsToArray(int n) {

    int [] temp = new int[String.valueOf(n).length()]; // Calculate the length of digits
    int i = String.valueOf(n).length()-1 ;  // Initialize the value to the last index

    do {
        temp[i] = n % 10;
        n = n / 10;
        i--;
    } while(n>0);

    return temp;
}

This will also maintain the order.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Salman Sayyed
  • 85
  • 1
  • 9
2

In Scala, you can do it like:

def convert(a: Int, acc: List[Int] = Nil): List[Int] =
  if (a > 0) convert(a / 10, a % 10 +: acc) else acc

In one line and without reversing the order.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sky
  • 2,509
  • 1
  • 19
  • 28
2

Try this!


int num = 1234; 

String s = Integer.toString(num); 

int[] intArray = new int[s.length()]; 


for(int i=0; i<s.length(); i++){
    intArray[i] = Character.getNumericValue(s.charAt(i));
}

CoderSam
  • 511
  • 1
  • 5
  • 16
1

Call this function:

  public int[] convertToArray(int number) {
    int i = 0;
    int length = (int) Math.log10(number);
    int divisor = (int) Math.pow(10, length);
    int temp[] = new int[length + 1];

    while (number != 0) {
        temp[i] = number / divisor;
        if (i < length) {
            ++i;
        }
        number = number % divisor;
        if (i != 0) {
            divisor = divisor / 10;
        }
    }
    return temp;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nayan
  • 578
  • 7
  • 13
1

You don't have to use substring(...). Use temp.charAt(i) to get a digit and use the following code to convert char to int.

char c = '7';
int i = c - '0';
System.out.println(i);
wannik
  • 12,212
  • 11
  • 46
  • 58
0

I can suggest the following method:

Convert the number to a string → convert the string into an array of characters → convert the array of characters into an array of integers

Here comes my code:

public class test {

    public static void main(String[] args) {

        int num1 = 123456; // Example 1
        int num2 = 89786775; // Example 2

        String str1 = Integer.toString(num1); // Converts num1 into String
        String str2 = Integer.toString(num2); // Converts num2 into String

        char[] ch1 = str1.toCharArray(); // Gets str1 into an array of char
        char[] ch2 = str2.toCharArray(); // Gets str2 into an array of char

        int[] t1 = new int[ch1.length]; // Defines t1 for bringing ch1 into it
        int[] t2 = new int[ch2.length]; // Defines t2 for bringing ch2 into it

        for(int i=0;i<ch1.length;i++) // Watch the ASCII table
            t1[i]= (int) ch1[i]-48; // ch1[i] is 48 units more than what we want

        for(int i=0;i<ch2.length;i++) // Watch the ASCII table
            t2[i]= (int) ch2[i]-48; // ch2[i] is 48 units more than what we want
        }
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Erfan
  • 163
  • 11
0

Use:

int count = 0;
String newString = n + "";
char [] stringArray = newString.toCharArray();
int [] intArray = new int[stringArray.length];
for (char i : stringArray) {
  int m = Character.getNumericValue(i);
  intArray[count] = m;
  count += 1;
}
return intArray;

You'll have to put this into a method.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • When you're answering questions, try to include a full working code sample. In some cases the person asking the question isn't clear on how a possible solution might work, so providing a code example that they may have to troubleshoot before they can apply it can be frustrating and more confusing. In this case, the original question is almost 6 years old, and already has an answer that's been accepted. If you can, try reviewing unanswered questions, and see if there are any there that you could help with. – Stephen R. Smith Jul 10 '17 at 06:24
0

I can't add comments to Vladimir's solution, but I think that this is more efficient also when your initial numbers could be also below 10.

This is my proposal:

int temp = test;
ArrayList<Integer> array = new ArrayList<Integer>();
do{
  array.add(temp % 10);
  temp /= 10;
} while  (temp > 1);

Remember to reverse the array.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Roberto Gimenez
  • 278
  • 4
  • 11
0

Here is the function that takes an integer and return an array of digits.

static int[] Int_to_array(int n)
{
    int j = 0;
    int len = Integer.toString(n).length();
    int[] arr = new int[len];
    while(n!=0)
    {
        arr[len-j-1] = n % 10;
        n = n / 10;
        j++;
    }
    return arr;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

First take input from the user as int, convert it into String, and make a character array of size of str.length(). Now populate a character array with a for loop using charAt().

Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String str = Integer.toString(num);
char [] ch = new char [str.length()];

for(int i=0; i<str.length(); i++)
{
    ch[i] = str.charAt(i);
}

for(char c: ch)
{
    System.out.print(c +" ");
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
0

Without using String, Integer, ArrayList, Math:

// Actual number
int n = 56715380;
            
            // Copy of the number
            int m = n;
            
            // Find no. of digits as length
            int ln = 0;
            while (m > 0) {
                m = m / 10;
                ln++;
            }
            
            // Copy of the length
            int len = ln;
    
            // Reverse the number
            int revNum = 0;
            ln--;
            int base;
            while (n > 0) {
                base = 1;
                for (int i = 0; i < ln; i++) {
                    base = base * 10;
                }
                revNum = revNum + base * (n % 10);
                n = n / 10;
                ln--;
            }
    
            // Store the reverse number in the array
            int arr[] = new int[len];
            for (int i = 0; revNum > 0; i++) {
                arr[i] = revNum % 10;
                revNum = revNum / 10;
            }
            
            // Print the array
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i]);
            }
0

This approach will maintain the same order of the digits in the given number in the resultant array and also won't be using any collection APIs.

  1. Starting with the basic approach of reversing a number say 1234. Get the last digit by modular division (%) by 10 and then divide the number by 10 to get the last digit. Do this until the number is greater than 0.

  2. So while getting each last digit you can store it in the array, so you need to initialize an array with the same number of digits in the number, you need to use a String functionality there. But with the above step, the resulting array will be in the reverse order of the digits in your number.

  3. So start adding the number from the last index of the array to the first index.

    int num = 1234;
    int[] ar = new int[String.valueOf(num).length()];
    int index = ar.length-1;
    
    while(num > 0) {
    
        ar[index--] = num % 10;
        num = num/10;
    }
    
    System.out.println(java.util.Arrays.toString(ar));
    
Arun Sudhakaran
  • 2,167
  • 4
  • 27
  • 52
0

temp2 = temp.substring(i); will always return the empty string "".

Instead, your loop should have the condition i<temp.length(). And temp2 should always be temp.substring(i, i+1);.

Similarly when you're printing out newGuess, you should loop up to newGuess.length but not including. So your condition should be i<newGuess.length.

tskuzzy
  • 35,812
  • 14
  • 73
  • 140
0

The <= in the for statement should be a <.

BTW, it is possible to do this much more efficiently without using strings, but instead using /10 and %10 of integers.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eamonn O'Brien-Strain
  • 3,352
  • 1
  • 23
  • 33
-1

I can not add comments to the decision of Vladimir, but you can immediately make an array deployed in the right direction. Here is my solution:

public static int[] splitAnIntegerIntoAnArrayOfNumbers (int a) {
    int temp = a;
    ArrayList<Integer> array = new ArrayList<Integer>();
    do{
        array.add(temp % 10);
        temp /= 10;
    } while  (temp > 0);

    int[] arrayOfNumbers = new int[array.size()];
    for(int i = 0, j = array.size()-1; i < array.size(); i++,j--) 
        arrayOfNumbers [j] = array.get(i);
    return arrayOfNumbers;
}

Important: This solution will not work for negative integers.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
M S
  • 1
-1

I modified Jon Skeet's accepted answer as it does not accept negative values.

This now accepts and converts the number appropriately:

public static void main(String[] args) {
    int number = -1203;
    boolean isNegative = false;
    String temp = Integer.toString(number);

    if(temp.charAt(0)== '-') {
        isNegative = true;
    }
    int len = temp.length();
    if(isNegative) {
        len = len - 1;
    }
    int[] myArr = new int[len];

    for (int i = 0; i < len; i++) {
        if (isNegative) {
            myArr[i] = temp.charAt(i + 1) - '0';
        }
        if(!isNegative) {
            myArr[i] = temp.charAt(i) - '0';
        }
    }

    if (isNegative) {
        for (int i = 0; i < len; i++) {
            myArr[i] = myArr[i] * (-1);
        }
    }

    for (int k : myArr) {
        System.out.println(k);
    }
}

Output

-1
-2
0
-3
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Phil
  • 435
  • 2
  • 9
  • 28
-3
public static void main(String k[])
{  
    System.out.println ("NUMBER OF VALUES ="+k.length);
    int arrymy[]=new int[k.length];
    for (int i = 0; i < k.length; i++)
    {
        int newGues = Integer.parseInt(k[i]);
        arrymy[i] = newGues;
    }
}
Rapptz
  • 20,807
  • 5
  • 72
  • 86