How can I convert a char to int in Java?

Haim Lvov :

(I'm new at Java programming)

I have for example:

char x = '9';

and I need to get the number in the apostrophes, the digit 9 itself. I tried to do the following,

char x = 9;
int y = (int)(x);

but it didn't work.

So what should I do to get the digit in the apostrophes?

khelwood :

The ASCII table is arranged so that the value of the character '9' is nine greater than the value of '0'; the value of the character '8' is eight greater than the value of '0'; and so on.

So you can get the int value of a decimal digit char by subtracting '0'.

char x = '9';
int y = x - '0'; // gives the int value 9

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=420201&siteId=1