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

2896 views
8

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;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculation);
editText=findViewById(R.id.et_regular_dep);
btnCalc=findViewById(R.id.btnCalculate);
btnCalc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String equation= editText.getText().toString();
CalculateResult(equation);
}
});

}

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

you can try stackoverflow.com/q/25225475/8089770.. 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

@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

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);

Log.d("no1",no1);
Log.d("no2",no2);
Log.d("ans",Math.pow(Double.parseDouble(no1),Double.parseDouble(no2))+"");
``````

posted this