Raghav Herugu
Raghav Herugu

Reputation: 546

Java calculator is crashing

I am making this really cool calculator app. Everything works, except for one thing. When the user presses an invalid equation, such as 1+, or 5-, it crashes. What I mean my crash is this: When it says, sorry, calculator has stopped. I tried fixing it, but it didn't work.

Java:

if (number1.getText().toString().contains("+")){
    String[] retVal;
    if (number1.getText().length() != 0) {
        //num1 = Float.parseFloat(num1 + "+");
        expr = number1.getText().toString();
        retVal = expr.split("\\+");
        if ((retVal[0].length() >= 2) || retVal[1].length() >= 2)
            return;
        num1 = Float.parseFloat(retVal[0]);
        num2 = Float.parseFloat(retVal[1]);
        resultnum = num1+num2;
        result.setText(String.valueOf(resultnum));
    }
    else {
        Toast.makeText(getApplicationContext(),"Please enter a valid math expression",Toast.LENGTH_SHORT).show();
        return;
    }

This is the line in which I added to fix the issue:(However, did not work)

if ((retVal[0].length() >= 2) || retVal[1].length() >= 2)
    return;

I am a beginner in Java programming. I am using Android Studio.

Upvotes: 0

Views: 119

Answers (1)

dave
dave

Reputation: 11975

I'm guessing as you don't include the exact error, but if your input is 1+ then

retVal = expr.split("\\+");

will return one string (not two), which means that

 retVal[1].length()

will cause an exception as retVal[1] does not exist.

To avoid this error, you should check retval after calling split() to see if it contains two elements. If it doesn't then tell your user their equation was invalid. For example,

 if (retVal.length != 2) {
     // Tell the user ...
 }

Upvotes: 4

Related Questions