如何计算两个整数值的结果,但从java中的jComboBox获取加法或乘法运算符
假设我有整数变量 a、b 和 c。
c = a + b; or c = a - b; or c = a / b; or c = a * b;
正如您所看到的,计算运算符需要在运行时动态传递。所以我有一个 jComboBox 运算符,因此用户将从 jcomboBox 中选择 +、-、* 或 /。
我如何获取 jCombobox selectedItem(可以是 /、*、- 或 + )并使用它来获取 c 的值。
例如。如果用户选择*,则表达式应为c = a * b,否则如果用户选择+,则表达式应为c = a + b。
assume i have integer variables a,b and c.
c = a + b; or c = a - b; or c = a / b; or c = a * b;
As you can see, the computation operator needs to be passed dynamically at run time. So i have a jComboBox of operators, so a user will select either a +, -, * or / from the jcomboBox.
how do i get the jCombobox selectedItem(which will be either /, *, -, or + ) and use it in getting the value of c.
Eg. if the user selects *, then the expression should be c = a * b else if the user selected say +, then the expression should be c = a + b.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里有一个“作弊”的方法。所有的解析都是由
ScriptEngine
完成的,我们只需要组装表达式的各个部分即可。另请参见
javax.script
包ScriptEngine
ScriptEngine
演示。 用于探索 JS 引擎的功能。Here is a way to 'cheat'. All the parsing is done by the
ScriptEngine
, we just need to assemble the parts of the expression.See Also
javax.script
packageScriptEngine
ScriptEngine
demo. for exploring the capabilities of the JS engine.您必须获取
JComboBox
的值,并对 Char 执行switch
语句(因为无法在字符串上switch
)来查看哪个是的,然后执行正确的操作。编辑:还不能
switch
字符串......(Java 7)You will have to get the Value of the
JComboBox
and do aswitch
statement on the Char (because cantswitch
on a string) to see which it is, then perform the correct operation.Edit: Cant
switch
on a string.... yet (Java 7)...
}
...
}
这个类似的问题可以提供帮助。
或者,您可以将组合框中显示的每个运算符与自定义计算器接口的实现相关联,该接口可以为您提供任意两个数字的结果。类似于:
关联可以是
HashMap
的形式。接口Calculator
可以对作为参数传递并作为结果返回的类型进行通用。这就是我解决问题的方法,但我确信可能有更简单的方法。This similar question can help.
Alternatively, you could associate each of the operators shown in a combobox with an implementation of a custom
Calculator
interface that gives you the result for any two numbers. Something like:The association can be of a form of
HashMap<String, Calculator>
. The interfaceCalculator
can be generic over the type you pass as parameter and return as result. That would be my approach to the problem, but I am sure there might be a simpler one.