简体   繁体   中英

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.

try Character.getNumericValue(char); this:

for (int i = 0; i < num1CharArray.length; i++){
    num1intarray[i] = Character.getNumericValue(num1CharArray[i]);
}
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]); 
       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM