2

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
    }
}
  • 1
    you can try https://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 – Vidhi Dave Nov 06 '18 at 05:41
  • [See this answer](https://stackoverflow.com/questions/14517390/adding-and-subtracting-for-bodmas-system) I hope this will help you. – Ali Ahmed Nov 06 '18 at 05:46
  • 1
    @VishvaDave this gives the number only after the keyword power or any other keyword –  Nov 06 '18 at 05:53
  • @Syed try my answer and let me know if any issues – Vidhi Dave Nov 06 '18 at 05:54

2 Answers2

0

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))+"");
Vidhi Dave
  • 5,614
  • 2
  • 33
  • 55
  • thank you @Vishva Dave . but it only solves if equation doesn't has other oprands like String eq= "2+3+5-2 *10 /2 power 3 " –  Nov 06 '18 at 05:59
  • yes for this formula you need to use other math functions or need to solve it manually i am not getting any exact solution for this – Vidhi Dave Nov 06 '18 at 06:00
  • 1
    well thank you @VishvaDave i will look for further answer –  Nov 06 '18 at 06:04
0

another easy way to do it

String eq = "2 power 3";
eq = eq.trim(); // if it has extra space at the start or end
String no1 = eq.split(" ")[0];
String no2 = eq.split(" ")[2];

Log.e("no1", no1);
Log.e("no2", no2);
Log.e("ans", Math.pow(Double.parseDouble(no1), Double.parseDouble(no2)) + "");
V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50