android - 数学函数 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
}
}
解决方案
试试这个 :
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))+"");
推荐阅读
- css - 如何覆盖 Angular8 .pug 文件中的样式?
- recursion - Automapper Parent Child Mapping 将 Grandchildren Properties 设置为 null
- istio - 使用 Istio 目标规则时是否有两个级别的负载均衡?
- c# - 加密文件内容并在读取 C# 时对其进行解密
- r - 以 R 中的另一列为条件对列重新排序
- python - 在matplotlib python中限制x轴
- html - 如何将鼠标悬停在使用伪选择器创建的整个形状上?
- java - SendEmail 在 Selenium Webdriver 中不起作用 - 未知 SMTP 主机:smtp.gmail.com;
- javascript - $(window).innerHeight() - “特定 div 的 id 高度”
- c - 尝试在 pset5 CS50 上检查我的解决方案时遇到问题