gpt4 book ai didi

java - 如何将字符串 "7/7"转换为 Int 1?

转载 作者:行者123 更新时间:2023-12-02 00:17:10 25 4
gpt4 key购买 nike

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

我尝试过将其直接转换为 double ,但无法使其工作。

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,但在命令行上输出错误。

最佳答案

您可以使用 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

关于java - 如何将字符串 "7/7"转换为 Int 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58085556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com