(我是Java编程的新手)
例如,我有:
char x = '9';
我需要获取引号中的数字,即数字9本身。我尝试了以下方法,
char x = 9;
int y = (int)(x);
但是它没有起作用。
那么我应该怎么做才能得到引号内的数字呢?
(我是Java编程的新手)
例如,我有:
char x = '9';
我需要获取引号中的数字,即数字9本身。我尝试了以下方法,
char x = 9;
int y = (int)(x);
但是它没有起作用。
那么我应该怎么做才能得到引号内的数字呢?
ASCII表按照字符'0'
的值为基准,以九递增到字符'9'
的值。
因此,你可以通过减去'0'
的值来得到十进制数字字符的整数值。
char x = '9';
int y = x - '0'; // gives the int value 9
如果你有一个'9'
字符,它会储存其ASCII代码,所以要获取int值,你有两种方法
char x = '9';
int y = Character.getNumericValue(x); //use a existing function
System.out.println(y + " " + (y + 1)); // 9 10
char x = '9';
int y = x - '0'; // substract '0' code to get the difference
System.out.println(y + " " + (y + 1)); // 9 10
实际上,这也可以工作:
char x = 9;
System.out.println(">" + x + "<"); //> < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10
您存储的是代码9
,它对应于水平制表符
(您可以在将其打印为String
时看到,但您也可以像上面所示一样将其用作int
)
您可以使用Character类的静态方法从字符中获取数字值。
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);
}
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);
}
char
都有相应的十进制数值。因此,您可以相减得到数值结果。自然而然地,数字0到9按顺序排列,所以数学计算起来更容易。 - David