【发布时间】:2020-12-29 01:29:49
【问题描述】:
我正在制作计算器应用程序。
我尝试制作删除按钮,但出现错误。
(1) 如果我在没有号码的情况下按退格键,应用程序会突然关闭。
(2) 如果我删除号码后按新号码,之前删除的号码又会出现。
我对此进行了很多搜索,但作为初学者我无法理解它们。
如果您能简单地解释一下,我将不胜感激。
public class MainActivity extends AppCompatActivity {
TextView workingsTV;
TextView resultsTV;
String workings = "";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTextView();
}
private void initTextView()
{
workingsTV = (TextView)findViewById(R.id.workingsTextView);
resultsTV = (TextView)findViewById(R.id.resultTextView);
}
private void setWorkings(String givenValue)
{
workings = workings + givenValue;
workingsTV.setText(workings);
}
public void equalsOnClick(View view)
{
Double result = null;
ScriptEngine engine = new ScriptEngineManager().getEngineByName("rhino");
try {
result = (Double) engine.eval(workings);
if (result != null)
{
int intVal = (int) result.doubleValue();
if (result == intVal)
{//Check if it's value is equal to its integer part
resultsTV.setText(String.valueOf(intVal));
}
else
{
resultsTV.setText(String.valueOf(result));
}
}
}
catch (ScriptException e) {
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
}
public void deleteOnClick(View view)
{
String del_number = workingsTV.getText().toString();
workingsTV.setText(del_number.substring(0,del_number.length() - 1));
}
【问题讨论】:
标签: java android calculator