0

I'm working on Android Studio, to make one field calculator

It will be just one Text field, button, and another text view. If I put "2+5*6" for example it must understand the operation.

Can anyone help me?

Check out my code please

public class MainActivity extends AppCompatActivity {
    public static final String equation = "[0-9]";

    String opr = " ";
    int[] result;
    int castedInt;
    String temp;
    String[] separated;
    EditText txte;
    TextView txtv;

    @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void buResult(View view) {
        txte = (EditText)findViewById(R.id.editText);
        for (int i = 0; i < txte.length(); i++) {
            if (Pattern.matches(txte.toString(), equation)) {
                separated[i] = txte.toString();
                temp = separated[i];
                castedInt = Integer.parseInt(temp.toString());
                result[i] = castedInt;
            }
            else {
                opr = txte.toString();
            }
            txtv.setText(result[i] + opr + result[i]);
        }
    }
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Malik Türk
  • 33
  • 1
  • 7

3 Answers3

0

You should implement reverse polish notation for string. Example code could be find here https://codereview.stackexchange.com/questions/120451/reverse-polish-notation-calculator-in-java

Community
  • 1
  • 1
Alex Baranowski
  • 1,014
  • 13
  • 22
0

As defined in the documentation regex must be a regular expression. You need to transform the user input into a regular expression.

Pattern.matches(String regex, CharSequence input)

Also you are always using the whole user input:

separated[i] = txte.toString();

All "separated" indexes will contain the same.

tknbr
  • 139
  • 1
  • 13
0

If it's Ok to use language support (instead of creating algorithm from scratch) you can use like this:

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
...
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
txtv.setText(engine.eval(txte.toString()));

*credits : stackoverflow.com/a/2605051/936786

Community
  • 1
  • 1
SerhiiK
  • 781
  • 8
  • 12