mrahh
mrahh

Reputation: 281

How to convert a char array to an int array?

Say I am using this code to convert a String (containing numbers) to an array of characters, which I want to convert to an array of numbers (int).

(Then I want to do this for another string of numbers, and add the two int arrays to give another int array of their addition.)

What should I do?

import java.util.Scanner;


public class stringHundredDigitArray {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        String num1 = in.nextLine();
        char[] num1CharArray = num1.toCharArray();
        //for (int i = 0; i < num1CharArray.length; i++){
            //System.out.print(" "+num1CharArray[i]);
        //}

        int[] num1intarray = new int[num1CharArray.length];
        for (int i = 0; i < num1CharArray.length; i++){
            num1intarray[i] = num1CharArray[i];
        }

        for (int i = 0; i < num1intarray.length; i++){ //this code prints presumably the ascii values of the number characters, not the numbers themselves. This is the problem.
            System.out.print(" "+num1intarray[i]);
        }
    }

}

I really have to split the string, to preferably an array of additionable data types.

Upvotes: 2

Views: 4606

Answers (3)

Joe
Joe

Reputation: 392

Short and simple solution!

int[] result = new int[charArray.length]; 
Arrays.setAll(result, i -> Character.getNumericValue(charArray[i])); 

Upvotes: 0

Benjamin
Benjamin

Reputation: 2286

Try This :
     int[] num1intarray = new int[num1CharArray.length];
    for (int i = 0; i < num1CharArray.length; i++)
        {
         num1intarray[i]=Integer.parseInt(""+num1CharArray[i]);
        System.out.print(num1intarray[i]); 
       }

Upvotes: 1

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28538

try Character.getNumericValue(char); this:

for (int i = 0; i < num1CharArray.length; i++){
    num1intarray[i] = Character.getNumericValue(num1CharArray[i]);
}

Upvotes: 3

Related Questions