如果用户没有在 EditText 框中输入值,我会尝试将其设置为 0(以防止崩溃错误 NumberFormatException Invalid int: ""),假设是因为没有可读取的整数值,因为在这种情况下用户没有输入。
我最近尝试了很多事情:
String boozeAmount = boozeConsumed.getText().toString();
if (boozeAmount == "" || boozeAmount == null){
boozeConsumed.setText("0");
boozeAmount = boozeConsumed.getText().toString();
}
int boozeOz = Integer.parseInt(boozeAmount) * 12;
double beerCalc = boozeOz * 4 * 0.075;
但它似乎仍然会抛出同样的错误,不知道为什么 int 值没有被设置为 0?
抛出错误
int boozeOz = Integer.parseInt(boozeAmount) * 12;
最佳答案
if (boozeAmount == "" || boozeAmount == null){
从您的解释中可以很容易地推断出这个特定的 if
语句返回 true
,这就是您的字符串值未设置为“0”的原因。
Java 中的字符串不是原始字符串,即它们不能与比较器 ==
进行比较。
您需要使用方法 equals
来比较字符串,如 boozeAmount.equals("")
。
Apache Commons 有一个 StringUtils可以检查字符串是否为 null 或空的实用程序。
查看 isEmpty
和 isBlank
。
关于android - 为什么此代码抛出 NumberFormatException Invalid int : ""?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21896610/