许多人会强制转换,但 java 不允许它。
异常 Cannot cast from String to int 表示 Java 编译器不允许 String 将 String 转换为 int。这是有道理的,因为两者不属于同一类型。
The Integer
Integer 对象包含 int 类型的单个属性。此类包含几种将 int 转换为 String 和将 String 转换为 int.
1 的方法 通过实例化新的 Integer(String s)
此构造函数分配一个包含整数的新对象:
public class 强制转换 {输出:
public static voidmain(String[] args) {
字符串 nbs = 12”;
int nb;
nb = 新整数(nbs);
System.out.println(nb);
}
}
12
2) 使用 Integer.valueOf(String s)
valueOf() 返回 java.lang.Integer,其中包含参数 String.
为了避免程序终止, 如果不遵守格式,我们将返回默认值。
References:
Oracle.com - Integer
JRJC-Convert 字符串到 int
public class Cast {输出:
public static void main(String[] args) {
String nbs = 12”;
int nb;
nb = 新整数(nbs);
System.out.println(nb);
}
}
12
3) 与 Integer.parseInt(String s)
The parseInt() 返回一个整数值,就像参数是在 valueOf(String s).
public class Cast {输出:
public static void main(String[] args) {
String nbs = 12”;
int nb;
nb = Integer.parseInt(nbs);
System.out.println(nb);
}
}
12
Exception NumberFormatException thrown
NumberFormatException 。原因是:
- 传递的参数至少包含一个非数字字符。
- 数字不像浮点 12.4f.
改进我们的程序
public class Cast {输出:
public static void main(String[] args) {
String nbs = 12.4s”;
int nb;
System.out.println(stringToInt(nbs,0));
}
public static int stringToInt(String value, int _default) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return _default;
}
}
}
0如果变量 nbs 不是数值,则函数 stringToInt() 默认返回 0.
References:
Oracle.com - Integer
JRJC-Convert 字符串到 int
Commentaires (0)
Laisser un commentaire
Connectez-vous pour commenter
Rejoignez la discussion et partagez vos connaissances avec la communauté
Chargement des commentaires...