猿问

如何将字符串“7/7”转换为 Int 1?

我正在尝试用 Java 制作一个计算器 GUI,但是我不知道如何将“7/7”转换为双精度数。


我尝试过将其直接转换为双精度数,但无法使其工作。


private class handler implements ActionListener{


    String answerString = "";

    int answerDouble;


    public void actionPerformed(ActionEvent e) {


        if(e.getSource() == clear) {

            answerString = "";

            result.setText(answerString);

        }

        if(e.getSource() == openBracket) {

            answerString = answerString + "(";

            result.setText(answerString);

        }

        if(e.getSource() == closeBracket) {

            answerString = answerString + ")";

            result.setText(answerString);

        }

        if(e.getSource() == divide) {

            answerString = answerString + "/";

            result.setText(answerString);

        }

        if(e.getSource() == seven) {

            answerString = answerString + "7";

            result.setText(answerString);

        }

        if(e.getSource() == equal) {

            answerDouble = Integer.parseInt(answerString);

            answerString = Double.toString(answerDouble);

            result.setText(answerString);

        }

    }


}

它应该显示 1 代表 7/7,但在命令行上输出错误。


海绵宝宝撒
浏览 142回答 1
1回答

慕桂英4014372

您可以使用JavaScript ScriptEngine来计算此类表达式:String expression = "7/7";ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("JavaScript");System.out.println(scriptEngine.eval(expression)); // you will have to handle ScriptException输出:1
随时随地看视频慕课网APP

相关分类

Java
我要回答