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.

1

3 Answers 3

3

try Character.getNumericValue(char); this:

for (int i = 0; i < num1CharArray.length; i++){
    num1intarray[i] = Character.getNumericValue(num1CharArray[i]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Alternative would be subtracting '0', but this works perfectly.
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]); 
       }

Comments

0

Short and simple solution!

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.