【发布时间】:2020-12-28 14:22:04
【问题描述】:
我正在制作计算器应用程序。即使我不使用双倍,它也会在结果中显示双倍。 示例)1+1 = 2.0
但我想要 1+1=2
当然,当有像 1.2+1.3= 2.5 这样的双倍时,我想保持双倍
我应该如何编辑?
我尝试这样编辑,但出现错误。
public void equalsOnClick(View view)
{
Integer result = null;
ScriptEngine engine = new ScriptEngineManager().getEngineByName("rhino");
try {
result = (int)engine.eval(workings);
} catch (ScriptException e)
{
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
if(result != null)
resultsTV.setText(String.valueOf(result.intValue()));
}
MainActivity
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);
} catch (ScriptException e)
{
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
if(result != null)
resultsTV.setText(String.valueOf(result.doubleValue()));
}
public void clearOnClick(View view)
{
workingsTV.setText("");
workings = "";
resultsTV.setText("");
leftBracket = true;
}
}
【问题讨论】:
-
您可以使用 DecimalFormat 类来确定双精度的格式。如果需要,您可以将其显示为 2、2.0 甚至更多小数位。
-
@LiveandLetLive 感谢您花时间帮助我。我真的是一个初学者,我从 youtube 获得了上述代码。我正在尝试理解您编写的代码。非常感谢您分享您的知识!!!!非常感谢!!!
-
不客气。
标签: java android calculator