如何将Java中的char转换为int?
问题描述:
(我在Java编程新)如何将Java中的char转换为int?
我有,例如:
char x = '9';
,我需要得到的撇号的数量,数字9本身。 我试图做到以下几点,
char x = 9;
int y = (int)(x);
但它没有工作。
那么我该怎么做才能得到撇号中的数字?
答
碰巧,字符'9'
的ascii/unicode值比'0'
(对于其他数字类似)的值大9。
所以你可以使用减法得到一个十进制数字字符的整数值。
char x = '9';
int y = x - '0'; // gives 9
答
我你有char '9'
,它将存储它的ASCII码,所以得到的int值,你有2种方式
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
码,这相当于一个horizontal tab
(你可以看到,当打印为String
,BU你也可以用它作为int
当你看到以上
答
如果你想获得一个字符的ASCII值,或者只是把它转换成一个int,你需要从一个char转换为一个int。
什么是铸造?投射就是当我们明确地将一个原始数据类型或一个类转换为另一个时。这是一个简单的例子。
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);
}
在这个例子中,我们有一个字符( 'a')中,我们把它转换为一个整数。打印出这个整数会给我们'a'的ASCII值。
答
您可以使用Character类中的静态方法从char中获取Numeric值。
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);
}
@HaimLvov:详细说明...看看网上的ASCII表。任何'char'都有该表中等价十进制值的数值。所以你可以减去其他任何一个来得到一个数字结果。自然,恰巧发生的是,字符0到9是为了使数学运作。 – David
更多关于https://stackoverflow.com/questions/3195028/please-explain-what-this-code-is-doing-somechar-48 – Andrew