简体   繁体   中英

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

charAt(i) will give you UTF-16 code unit value of the integer for example in your case, UTF-16 code unit value of 1 is 49. To get integer representation of the value, you can subtract '0'(UTF-16 code unit value 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

temp.charAt(i) is basically returning you characters. You need to extract the Integer value out of it.

You can use:

newGuess[i] = Character.getNumericValue(temp.charAt(i));

Output

1
2
3

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] = Character.getNumericValue(temp.charAt(i));
        }
        for (int i : newGuess) {
            System.out.println(i);
        }
    }
}

To add a little Java 8 niceties to the mix which allows us to pack everything up neatly, you can optionally do:

int i = 123;
int[] nums = Arrays.stream(String.valueOf(i).split(""))
        .mapToInt(Integer::parseInt)
        .toArray();

Here we get a stream to an array of strings created by splitting the string value of the given integer's numbers. We then map those into integer values with Integer#parseInt into an IntStream and then finally make that into an array.

As your interest is to get as an integer value of an string. Use the method parse int Integer.parseInt() . this will return as integer. Example : int x =Integer.parseInt("6"); It will return integer 6.

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