Invert string containing numbers

Asked

Viewed 90 times

1

Using this code as a test, whose goal is to invert a string containing numbers.

Input: 0123456789

Output: [57, 56, 55, 54, 53, 52, 51, 50, 49, 48] unlike [9, 8, 7, 6, 5, 4, 3, 2, 1, 0].

public class exercise33 {

    public static void main(String[] agrs) {    


        Scanner sc = new Scanner(System.in);

        String hold = "";
        int j = 0;

        System.out.print("Enter a number: ");
        hold = sc.next();


        int[] test = new int[hold.length()];


        for(int i = hold.length() - 1 ; i >= 0 ; i--) {
            test[j++] = hold.charAt(i);
        }

        System.out.print(Arrays.toString(test));;

        sc.close();
    }

}

1 answer

3


It happens because you’re dealing with text, and not with numbers. Although the text contains digits from 0 to 9, they are still characters, not numerical values.

Only that the char, despite the name, it is also a numeric type. So when you take a char returned by charAt and assigns to a int, the character value in the ascii table. Example:

char c = '0';
System.out.println(c); // 0
int n = c;
System.out.println(n); // 48
System.out.println(c == 48); // true

To do what you need (transform the character 0 number 0, etc.), just subtract 48, which is the value of the character 0. Thus, each int will have its correct value (because the values are consecutive, the character 1 has the value 49, the 2 is 50, etc.):

for (int i = hold.length() - 1; i >= 0; i--) {
    test[j++] = hold.charAt(i) - 48;
}

Or else:

for (int i = hold.length() - 1; i >= 0; i--) {
    test[j++] = hold.charAt(i) - '0';
}

Only to complement, there are better ways to invert a string.

  • Other form is, instead of using an array, use a string to receive the result: test += hold.charAt(i);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.