0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Raghav Herugu
  • 545
  • 7
  • 19
  • 3
    When you say "crashes", what do you mean? Do you you get an exception? A stack-trace? Please include these in your question so we can help you fix the problem. – dave Nov 14 '18 at 22:03
  • 1
    Also, check first after `retVal = expr.split(...)` to see if you have 2 entries; if it didn't split to 2 (or more) entries, then `retVal[1]` will not be valid. Such as `if (retVal.length < 2) { //do error }` – KevinO Nov 14 '18 at 22:05
  • There are some troubleshooting instructions in [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) The error log probably said `ArrayIndexOutOfBoundsException` and the code line number where it happens. Then you would put a break point there, debug the app and realize that `retVal` only has one element after the split. – Markus Kauppinen Nov 14 '18 at 22:09
  • 1
    *"Please help me as soon as possible.."* No. I'm spending my effort helping people with better time management skills. If you need urgent help, you're already too late for mine. – Andrew Thompson Nov 15 '18 at 00:55

1 Answers1

4

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 ...
 }
dave
  • 11,641
  • 5
  • 47
  • 65