简体   繁体   English

按下按钮会导致应用崩溃

[英]Button pressing causes app crash

In eclipse i tried making a calculator. 在日食中,我试图做一个计算器。 I had 2 separate text fields for two numbers and addition subtraction buttons. 我有2个单独的文本字段,包含两个数字和加减按钮。 When i press add or sub button without entering values app crashes. 当我按添加或子按钮而不输入值时,应用崩溃。 Is there any possible way out? 有没有可能的出路?

public void onClick(View v) {
    // TODO Auto-generated method stub
    String l1= et1.getText().toString();
    String l2= et2.getText().toString();
    int a=0, b=0;

    double result=0.0;
    a=Integer.parseInt(l1);
    b=Integer.parseInt(l2);

    switch(v.getId())
    {
    case R.id.b1:

        result=a+b;
        break;
    case R.id.b2:
        result=a-b;
        break;
    case R.id.b3:
        result = a*b;
        break;
    case R.id.b4:
        if(b==0)
        {
            open("Cannot Divide By zero");
        }
        else result = a/b;
        break;
    }
    et3.setText(Double.toString(result));
}

If no value was entered in the EditText, the Integer.parseInt() method will crash because the String passed is not a valid number. 如果没有在EditText中输入任何值,则Integer.parseInt()方法将崩溃,因为传递的字符串不是有效数字。

a=Integer.parseInt(l1);
b=Integer.parseInt(l2);

Replace with: 用。。。来代替:

if(!l1.isEmpty() && !l2.isEmpty()){
   a=Integer.parseInt(l1);
   b=Integer.parseInt(l2);
}else{
   Toast.makeText(this,"Something is wrong!",Toast.LENGTH_SHORT).show();
}

Note: the code above only check if was entered something in the EditTexts, you should check if it's a number also. 注意:上面的代码仅检查是否在EditTexts中输入了某些内容,您还应该检查它是否也是一个数字。 i will leave that part for you to learn ;) 我会把那部分留给你学习;)

Clayton Oliveira's answer is good. 克莱顿·奥利维拉(Clayton Oliveira)的回答很好。 It handles the empty input situation. 它处理空输入情况。 This code handles all the cases where l1, l2 can not be parsed to integer. 该代码处理无法将l1,l2解析为整数的所有情况。

try{
    a=Integer.parseInt(l1);
    b=Integer.parseInt(l2);
} catch(NumberFormatException e) {
    Log.e("Wrong input", e.getMessage());
}

You should post more detail about your code to get many support at here, but i guess you have get this problem: 您应该在此处发布有关代码的更多详细信息,以获得更多支持,但是我想您已经遇到了这个问题:

Add or Sub function net two integer number to calculate but you not enter any value (number value) into Edittext (text field) and value is null or empty string so wrong. Add或Sub函数计算两个整数来计算,但是您没有在Edittext(文本字段)中输入任何值(数字值),并且值是null或空字符串,因此错误。

Solution: - You set edittext to require input number value not string - you need check input value is empty (if true then do not something) to before calculate. 解决方案:-您将edittext设置为要求输入数字值而不是字符串-您需要在计算之前检查输入值是否为空(如果为true,则为空)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM