Anu Tiwari Anu Tiwari - 2 months ago 14
Java Question

Integer printing wrong value

When converting an integer to int array, for example 123 to {1,2,3}, I am getting values {49,50,51}.
Not able to find what is wrong with my code.

public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = temp.charAt(i);
}
for (int i : newGuess) {
System.out.println(i);
}
}
}


Output:


49

50

51

Answer

charAt(i) will give you ASCII value of the integer for example in your case, ASCII value of 1 is 49. To get integer representation of the value, you can subtract '0'(ASCII 48) from i.

public class Test {
    public static void main(String [] args) {
        String temp = Integer.toString(123);
        int[] newGuess = new int[temp.length()];
        for (int i = 0; i < temp.length(); i++) {
            newGuess[i] = temp.charAt(i);
        }
        for (int i : newGuess) {
            System.out.println(i - '0');
        }
    }
}

Output:

1

2

3