如何在计算器上用int显示结果?

mfuanj7w  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(663)

我正在做计算器应用程序。即使我不使用double,结果也会显示double。例)1+1=2.0
但我想要1+1=2
当然,我想保留double,当有double时,比如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, "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;
    }
}
fhity93d

fhity93d1#

因为你已经宣布 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) 不会引发异常。

1tu0hz3e

1tu0hz3e2#

使用模运算符检查double是整数(结果%1==0)还是math.floor,然后检查结果是否更改。
如果是,则可以使用integer.valueof(result)
顺便说一下,integer有一个内置的tostring方法。

相关问题