如果你想获取字符对应的 ASCII 码值,可以直接将字符赋值给一个整数类型的变量,因为 Java 中字符类型在参与运算时会自动转换为对应的整数(ASCII 码值)。
java
public class CharToAscii {
public static void main(String[] args) {
char ch = 'A';
int asciiValue = ch;
System.out.println("字符 " + ch + " 对应的 ASCII 码值是: " + asciiValue);
}
}
字符 '0'-'9' 转换为对应的整数 0 - 9
如果字符是 '0' 到 '9' 之间的数字字符,要将其转换为对应的整数 0 到 9,可以通过减去字符 '0' 来实现。
java
public class DigitCharToInt {
public static void main(String[] args) {
char digitChar = '5';
int digit = digitChar - '0';
System.out.println("字符 " + digitChar + " 对应的整数是: " + digit);
}
}
字符串形式的数字转换为整数或其他数字类型
如果是一个字符串形式的数字,例如 "123",可以使用 Integer
、Double
等包装类的 parseXxx
方法将其转换为对应的数字类型。
java
public class StringToNumber {
public static void main(String[] args) {
String numberStr = "123";
int intValue = Integer.parseInt(numberStr);
System.out.println("字符串 " + numberStr + " 转换为整数是: " + intValue);
String doubleStr = "3.14";
double doubleValue = Double.parseDouble(doubleStr);
System.out.println("字符串 " + doubleStr + " 转换为双精度浮点数是: " + doubleValue);
}
}