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");}
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
Please, use contains()
without escaping and split()
with escaping
current.contains("+")
current.split("\\+")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.