如何将 Java 字符转换为int
原文:https://www.studytonight.com/java-type-conversion/how-to-convert-java-char-to-int
在 Java 中,可以通过以下方式将字符值转换为 int
直接将字符值赋给将返回字符 ASCII 值的 int。
使用字符串值方法
1.获取 ASCII 值
当一个字符值被直接赋值为 int 时,它返回赋给该字符值的整数 ASCII 值。
例 1:
这里,返回与 char 变量相关联的 ASCII 值。
public class StudyTonight
{
public static void main(String args[])
{
char c1 = 'm';
char c2 = 'M';
int n1 = c1;
int n2 = c2;
System.out.println("The equivalent ASCII value is " +n1);
System.out.println("The equivalent ASCII value is " +n2);
}
}
等效 ASCII 值为 109 等效 ASCII 值为 77
2.Character.getNumericValue()
方法
getNumericValue() 方法是字符类的一部分,该类返回字符的数值(int)。
例 2:
这里,使用character . getnumericvalue()方法返回分配给该字符的 int 值。
public class StudyTonight
{
public static void main(String args[])
{
char ch = '8';
int n = Character.getNumericValue(ch);
System.out.println("The int value is : " +n);
}
}
int 值为:8
3.Integer.parseInt()
法
parseInt()
方法是Integer
类的一部分,返回指定对象值的 int 值。
例 3:
这里先将字符值转换为字符串,然后使用parseInt()
方法转换为整数。整数值返回到指定的字符值。
public class StudyTonight
{
public static void main(String args[])
{
char ch = '5';
int n = Integer.parseInt(String.valueOf(ch));
System.out.println("The integer value is " +n);
}
}
整数值为 5