【发布时间】:2018-03-02 18:54:09
【问题描述】:
(我是 Java 编程新手)
例如:
char x = '9';
我需要得到撇号中的数字,即数字 9 本身。 我尝试执行以下操作,
char x = 9;
int y = (int)(x);
但是没有用。
那么我应该怎么做才能得到撇号中的数字呢?
【问题讨论】:
标签: java char type-conversion int
(我是 Java 编程新手)
例如:
char x = '9';
我需要得到撇号中的数字,即数字 9 本身。 我尝试执行以下操作,
char x = 9;
int y = (int)(x);
但是没有用。
那么我应该怎么做才能得到撇号中的数字呢?
【问题讨论】:
标签: java char type-conversion int
ASCII 表的排列使得字符'9' 的值比'0' 的值大9;字符'8'的值比'0'的值大8;等等。
所以你可以通过减去'0'得到一个十进制数字char的int值。
char x = '9';
int y = x - '0'; // gives the int value 9
【讨论】:
char 在该表中都有其等效十进制值的数值。因此,您可以从任何其他中减去任何一个以获得数字结果。很自然地,字符 0 到 9 是按顺序排列的,所以数学很有效。
你有char '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 代码,它对应于horizontal tab(打印时您可以看到String,但您也可以将其用作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 中获取数值。
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);
}
【讨论】: