如何解决如何在计算器上用 Int 显示结果?
我正在制作计算器应用程序。即使我不使用 double,它也会在结果中显示 double。 示例)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()));
}
主活动
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,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;
}
}
解决方法
使用模运算符检查双精度是否为整数 (结果 %1 ==0) 或 Math.floor 然后检查结果是否改变。
如果是,你可以使用Integer.valueOf(result)
顺便说一下,Integer 有一个内置的 toString 方法。
,发生这种情况是因为您声明了类型为 result
的 Double
。因此,除非您将它的 doubleValue()
转换为 int
并将其设置为 resultsTV
,否则它的 double
值将在那里设置。
按如下方式更改您的方法定义:
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();
}
}
请注意,我还在 resultsTV.setText
块中移动了 try-catch
,以便它仅在 result = (Double)engine.eval(workings)
不引发异常时才被执行。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。