首页 > 解决方案 > 数学函数 Power from String ("2 power 3")

问题描述

我必须在从字符串中获取方程时执行 pow 函数,例如"2 power 3". 我知道有函数Math.pow(a, b),我也可以用它for loop来实现这一点,但问题是这两种方法都需要整数,而且我在字符串中有方程。我不知道如何解析这个字符串并将两个变量分开。还有另一个问题。我的方程式也可能变得有点复杂。例如它可能像"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
    }
}

标签: androidstringpow

解决方案


试试这个 :

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

推荐阅读