如何在 Android 中将 java.lang.String 转换为 int?我写了这段代码,但它不起作用:
public static String code;
...
db.insertQuote(Integer.parseInt(code));
我使用这段代码,当我阅读 NFC 标签时,我希望这个函数能够运行,但它给了我一个错误,因为我使用真正的手机进行测试,我无法理解发生了什么。
int i=Integer.parseInt(stringvalue);
因此,假设代码具有除数字以外的其他值,您应该调试并测试 的值code
,如果它为空白,它也会抛出NumberFormatException
,或者如果它的 NullPointerException,那么字符串代码可能尚未初始化。
您确定Code
在调用之前已正确初始化Integer.parseInt(Code)
吗?如果Code
仍然只是定义,但没有初始化(没有分配给Code
),那么这就是你的问题。
除此之外,您必须确保它Code
确实是一个数字,所以我建议以下内容:
public static String Code;
... //rest of your code here
if(Code != null)
{
try
{
db.insertQuote(Integer.parseInt(Code));
}
catch(NumberFormatException e)
{
//execution will get here if Code is not a number
//insert code to handle this chase
}
}
String number;
int x = Integer.valueOf(number);
最简单的答案是:
int i = Integer.parseInt(StringValue);