1

In eclipse i tried making a calculator. I had 2 separate text fields for two numbers and addition subtraction buttons. 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));
}
MochaBongo
  • 13
  • 3

3 Answers3

1

If no value was entered in the EditText, the Integer.parseInt() method will crash because the String passed is not a valid number.

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. i will leave that part for you to learn ;)

Clayton Oliveira
  • 625
  • 1
  • 6
  • 15
1

Clayton Oliveira's answer is good. It handles the empty input situation. This code handles all the cases where l1, l2 can not be parsed to integer.

try{
    a=Integer.parseInt(l1);
    b=Integer.parseInt(l2);
} catch(NumberFormatException e) {
    Log.e("Wrong input", e.getMessage());
}
Jeffrey Chen
  • 1,777
  • 1
  • 18
  • 29
0

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.

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.

GiapLee
  • 436
  • 2
  • 8