我正在尝试用 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,但在命令行上输出错误。
1 回答
慕桂英4014372
TA贡献1871条经验 获得超13个赞
您可以使用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
添加回答
举报
0/150
提交
取消