0

I have this problem where I need to create a method that takes in a String and creates an integer array of each character. I have checked each step of the for loop and the array before and after the loop, and I am lost.

It correctly shows each character as '3' '4' and '5', however once it is inserted into the array, it always prints [51, 52, 53]. I am so lost where those numbers even came from? Thanks so much...

public class CodingBat {
public static void main(String[] args) {
    String text = "345";
    int[] create = new int[text.length()];
    for(int i = 0; i < text.length(); i++) {
        System.out.printf("Current array: %s\n", Arrays.toString(create));
        //System.out.println(text.charAt(i));
        create[i] = text.charAt(i);
        System.out.printf("Adding %c\n", text.charAt(i));
    }
    System.out.println(Arrays.toString(create));
}

}

jovartzy
  • 9
  • 1
  • `char` is 16-bit type which stores number representing *index* of character in Unicode Table and that is what you are seeing. If you want to get `int` corresponding to digit you can take index of that digit and subtract index of `'0'` character (something like `create[i] = text.charAt(i) - '0';`). Now where is that duplicate... – Pshemo Jul 01 '20 at 19:48
  • Those numbers are the ascii representation of those characters. You could subtract the value of the character '0' in order to get the digit value. – NomadMaker Jul 01 '20 at 19:49

1 Answers1

1

You're inserting a char into a int array, if i remember, the numbers that you see printing the array are the ASCII code.

So, if you want to get the number, use:

create[i] = Character.getNumericValue(text.charAt(i))