JAVA 字符串有中文可以转换为int类吗?
public class var07{
public static void main(String[]args){
String s1 = "东";
int num1 =Integer.parseInt(s1);
System.out.println(num1);
}
}
然后就报错为
是语法出现什么错误了吗?求解答过程
这种字符串不可能转换成int
中文怎么可能转换为数字啊
这个只能转换字符串中的数字,比如String s1 = "123"这样的
东应该被转成数字多少
public static int parseInt(String s, int radix)
throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
if (s == null) {
// Android-changed: Improve exception message for parseInt.
throw new NumberFormatException("s == null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
转int是通过ascii得到的,汉字的ascii值很大的
public class var07{
public static void main(String[]args){
String s1 = "东";
System.out.println(s1.charAt(0)+0);
}
}
建议你看下这篇博客java中Int类型数字转中文不能哦,字符串中必须全部是数字才可以
那怎么转?一个中文你想让它转成什么数字?
只有纯数字的字符串,才能被转成int型