如何在Java中将字符转换为int?
(我是Java编程新手) 例如,我有:如何在Java中将字符转换为int?,java,char,type-conversion,int,Java,Char,Type Conversion,Int,(我是Java编程新手) 例如,我有: char x = '9'; 我需要得到撇号中的数字,数字9本身。 我试着做了以下几件事 char x = 9; int y = (int)(x); 但它不起作用 那么,我应该怎么做才能得到撇号中的数字呢?ASCII表格的排列方式是,字符'9'的值比'0'的值大9;字符'8'的值比'0'的值大八;等等 因此,您可以通过减去'0'得到十进制数字字符的int值 char x = '9'; int y = x - '0'; // gives the int v
char x = '9';
我需要得到撇号中的数字,数字9本身。
我试着做了以下几件事
char x = 9;
int y = (int)(x);
但它不起作用
那么,我应该怎么做才能得到撇号中的数字呢?ASCII表格的排列方式是,字符
'9'
的值比'0'
的值大9;字符'8'
的值比'0'
的值大八;等等
因此,您可以通过减去'0'
得到十进制数字字符的int值
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;
System.out.println(">" + x + "<"); //> < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10
charx=9;
System.out.println(“>”+x+“如果您想要获取字符的ASCII值,或者只是将其转换为int,则需要从字符转换为int
什么是强制转换?强制转换是当我们显式地从一个primitve数据类型或类转换为另一个时。下面是一个简单的示例
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'),并将其转换为整数。打印出这个整数将得到ASCII值'a'。您可以使用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);
}
@海姆尔沃夫:为了详细说明……请看一看在线任意位置的ASCII表。任何char
在该表中都有其等效十进制值的数值。因此,您可以从任何一个表中减去任何一个,以得到一个数值结果。很自然,字符0到9是有序的,因此数学工作正常。更多关于@David的信息-这个答案比字符好吗。getNumericValue(x)在性能方面?在ASCII“0”=48,1='49'等中,我们找到了一个关于这个理论的有用解释:OP不想得到ASCII值,他想在将这个字符解释为实际数时得到这个值。对于“9”,他想返回9而不是57(ASCII值为'9')
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);
}