如何在 Java 中将一个 char 转换为 int?

(我是 Java 编程的新手)

我举个例子:

char x = '9';

我需要得到撇号里的数字,数字9本身。 我试着做了以下几件事,

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

但没成功。

那么我该怎么做才能得到撇号中的数字呢?

256285 次浏览

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

I you have the char '9', it will store its ASCII code, so to get the int value, you have 2 ways

char x = '9';
int y = Character.getNumericValue(x);   //use a existing function
System.out.println(y + " " + (y + 1));  // 9  10

or

char x = '9';
int y = x - '0';                        // substract '0' code to get the difference
System.out.println(y + " " + (y + 1));  // 9  10

And it fact, this works also :

char x = 9;
System.out.println(">" + x + "<");     //>  < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10

You store the 9 code, which corresponds to a horizontal tab (you can see when print as String, bu you can also use it as int as you see above

If you want to get the ASCII value of a character, or just convert it into an int, you need to cast from a char to an int.

What's casting? Casting is when we explicitly convert from one primitve data type, or a class, to another. Here's a brief example.

public class char_to_int
{
public static void main(String args[])
{
char myChar = 'a';
int  i = (int) myChar; // cast from a char to an int
System.out.println ("ASCII value - " + i);
}

In this example, we have a character ('a'), and we cast it to an integer. Printing this integer out will give us the ASCII value of 'a'.

You can use static methods from Character class to get Numeric value from char.

char x = '9';


if (Character.isDigit(x)) { // Determines if the specified character is a digit.
int y = Character.getNumericValue(x); //Returns the int value that the
//specified Unicode character represents.
System.out.println(y);
}