这是为什么code抛出NumberFormatException的无效INT:""? [英] Why is this code throwing NumberFormatException Invalid int: ""?

查看:225
本文介绍了这是为什么code抛出NumberFormatException的无效INT:""?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图得到它,​​如果用户不输入在箱子的EditText的值,初始值设置为0(以prevent崩溃错误NumberFormatException的无效INT:),这是抛出假定因为没有整数值来读取,由于用户在这种情况下,没有输入之一。

我已经尝试了很多事情最近这样的:

 字符串boozeAmount = boozeConsumed.getText()的toString()。        如果(boozeAmount ==|| boozeAmount == NULL){
            boozeConsumed.setText(0);
            boozeAmount = boozeConsumed.getText()的toString()。
        }
        INT boozeOz =的Integer.parseInt(boozeAmount)* 12;
        双beerCalc = boozeOz * 4 * 0.075;

但似乎仍然抛出了同样的错误,不知道为什么INT值没有被设置为0?

投掷误差

  INT boozeOz =的Integer.parseInt(boozeAmount)* 12;


解决方案

 如果(boozeAmount ==|| boozeAmount == NULL){

可以从你的解释很容易推断出这个特殊的如果语句返回真正,这就是为什么你的字符串值没有被设置为0。

Java中的字符串不是原始的,即他们无法比较 == 进行比较。
你需要在使用等于方法来比较字符串,如boozeAmount.equals()

Apache的百科全书有一个<一个href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html\"相对=nofollow> StringUtils的实用工具,可以检查是否字符串是null或空。
看看的isEmpty 的isBlank

I'm trying to get it to if a user doesn't enter a value in the EditText boxes, the initial value is set to 0 (to prevent the crash error NumberFormatException Invalid int: "") which is thrown assuming because there is no integer value to read, since the user didn't input one in this case.

I've tried a number of things most recently this:

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;

But it seems to still throw the same error, not sure why the int values aren't being set to 0?

Throwing error on

int boozeOz = Integer.parseInt(boozeAmount) * 12;

解决方案

if (boozeAmount == "" || boozeAmount == null){

It can be easily deduced from your explanation that this particular if statement is returning true, that's why your string value is not being set to "0".

Strings in Java are not primitive, i.e they cannot be compared with the comparator ==. You need to use the method equals to compare strings, as in boozeAmount.equals("").

Apache Commons has a StringUtils utility that can check if strings are null or empty. Check out isEmpty and isBlank.

这篇关于这是为什么code抛出NumberFormatException的无效INT:&QUOT;&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆