0

I`m trying to write a Calculator app for android. for 4 main operators (-*/+) I used this method and for 3 of them it work without out any problems but for + operator it cannot recognize the + sign in the string i through at it. he is my code for / and + operators :

case R.id.buttonEql:
            current=show.getText().toString();
           if(current.contains("/"))
           { current+=input.getText().toString();
               show.setText(current);
              parts  = current.split("/");
           firstNumber = Integer.parseInt(parts[0]);
           secondNumber = Integer.parseInt(parts[1]);
              operationResult = firstNumber/secondNumber;
               show.setText("");
               show.setText(String.valueOf(operationResult));
               input.setText("0");
           }
           else if (current.contains("\\+"))
           {current=show.getText().toString();
               current+=input.getText().toString();
               show.setText(current);
               parts  = current.split("\\+");
               firstNumber = Integer.parseInt(parts[0]);
               secondNumber = Integer.parseInt(parts[1]);
               operationResult = firstNumber+secondNumber;
               show.setText("");
               show.setText(String.valueOf(operationResult));
               input.setText("0");}
Hossain Ehsani
  • 385
  • 2
  • 16
  • 3
    Why are you escaping it? Wouldn't "+" suffice? – rotgers Apr 21 '17 at 22:12
  • according to this post: http://stackoverflow.com/a/3481842/5752702 it should work like this. I tried your solution with no luck. now I restart the computer and tried it again it works without \\. thank you – Hossain Ehsani Apr 21 '17 at 22:17
  • I doubt that is due to restarting your computer, but ok. :-) Other people suggested the same answer, probably mark one of those as accepted. – rotgers Apr 21 '17 at 22:19
  • It also seems that u are using switch statement. Maybe put the code in the case in a new function (with arguments). Makes it a lot easier to read if it is a large switch statement. – rotgers Apr 21 '17 at 22:24

2 Answers2

4

In else if condition, what about doing just current.contains("+").

you are passing a regular expression (escaping it) which you should not for String contains function. Check on Java API Doc for String

neeranzan
  • 131
  • 5
2

Please, use contains() without escaping and split() with escaping

current.contains("+")

current.split("\\+")
v.ladynev
  • 19,275
  • 8
  • 46
  • 67