2

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.

mrahh
  • 281
  • 1
  • 4
  • 13

3 Answers3

3

try Character.getNumericValue(char); this:

for (int i = 0; i < num1CharArray.length; i++){
    num1intarray[i] = Character.getNumericValue(num1CharArray[i]);
}
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
1
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]); 
       }
Benjamin
  • 2,257
  • 1
  • 15
  • 24
0

Short and simple solution!

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