Math function Power from String ("2 power 3")

2896 views android

I have to perform a pow function while getting equation from string like "2 power 3". I know there is function Math.pow(a, b) and also I can use for loop to achieve this , but the problem is both methods needs integer and I have equation in string. I don't know how to parse this string and separate both variables. And there is another problem. my equation could get little bit complex as well. for instance it could be like "2+3*5/5 power 2"

public class CalculationActivity extends AppCompatActivity {

    EditText editText;
    Button btnCalc;

    protected void onCreate(Bundle savedInstanceState) {
        btnCalc.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String equation= editText.getText().toString();


    private void CalculateResult(String equation) {
        // here to perform power function

answered question

you can try with this you can acheive starting numbers/equation before word "power" and after the word "power". and can parse it to int and perform that pow method on that

See this answer I hope this will help you.

@VishvaDave this gives the number only after the keyword power or any other keyword

@Syed try my answer and let me know if any issues

1 Answer


Try this :

 String eq = "2 power 3";
 String no2 = eq.substring(eq.indexOf("power") + 6 , eq.length());
 String no1 = eq.substring(0,eq.indexOf("power")-1);


posted this

Have an answer?


Please login first before posting an answer.