我想知道如何防止数学运算符重复。
例如,这是我得到的9+++++****----////
有什么办法可以防止手术重复吗?非常感谢你的帮助。
下面是我的代码:
public class MyActivity extends AppCompatActivity implements View.OnClickListener {
Button button_clear, button_addition, button_dot, button_multiply,button_divide,button_subtract,
button_one,button_two,button_three,button_four,button_five,button_six,button_seven,button_eight,
button_nine,
button_zero,button_equal;
TextView displayTv, result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
displayTv=findViewById(R.id.displayTV);
result=findViewById(R.id.answerCalculated);
asignId(button_clear, R.id.clear);
asignId(button_addition, R.id.addition);
asignId(button_subtract, R.id.subtract);
asignId(button_multiply, R.id.multiplication);
asignId(button_divide, R.id.divide);
asignId(button_dot, R.id.dot);
asignId(button_one, R.id.button_one);
asignId(button_two, R.id.button_two);
asignId(button_three, R.id.button_three);
asignId(button_four, R.id.button_four);
asignId(button_five, R.id.button_five);
asignId(button_six, R.id.button_six);
asignId(button_seven, R.id.button_seven);
asignId(button_eight, R.id.button_eight);
asignId(button_nine, R.id.button_nine);
asignId(button_zero, R.id.button_zero);
asignId(button_equal,R.id.button_equal);
}
private void asignId(Button btn, int id) {
btn=findViewById(id);
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
//set view to button
Button button=(Button)view;
//get buttonText
String buttonText=button.getText().toString();
//get DisplayedText
String displayedText=displayTv.getText().toString();
//displayed text plus button text
displayedText=displayedText+buttonText;
displayTv.setText(displayedText);
String finalResult=getResult(displayedText);
switch (view.getId()){
case R.id.clear:
displayTv.setText("");
result.setText("0");
break;
case R.id.button_equal:
if(!finalResult.equals("ERR")){
result.setText(finalResult);
}
}
//
}
private String getResult(String data) {
try{
Context context = Context.enter();
context.setOptimizationLevel(-1);
Scriptable scriptable = context.initStandardObjects();
String finalResult = context.evaluateString(scriptable,data,"Javascript",1,null).toString();
if(finalResult.endsWith(".0")){
finalResult = finalResult.replace(".0","");
}
return finalResult;
}catch (Exception e){
return "Err";
}
}
}
1条答案
按热度按时间k4emjkb11#
你可以做的是在
onClick
中检查displayedText
中的最后一个字符,如果它是一个数学运算符,那么你就把它从文本中删除,下面是一些代码:isMathOperator只是一个方法,用来检查字符是否是4个数学运算符之一: