如何计算两个整数值的结果,但从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 else如果用户选择了说+,那么表达式应该是c = a + b

这是一种’欺骗’的方法。 所有的解析都是由ScriptEngine完成的,我们只需要组装表达式的各个部分。

ScriptEngine计算器

 import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.script.*; class ScriptEngineCalculations { public static void main(String[] args) { final ScriptEngine engine = new ScriptEngineManager(). getEngineByExtension( "js" ); String[] ops = {"+", "-", "*", "/"}; JPanel gui = new JPanel(new BorderLayout(2,2)); JPanel labels = new JPanel(new GridLayout(0,1)); gui.add(labels, BorderLayout.WEST); labels.add(new JLabel("a")); labels.add(new JLabel("operand")); labels.add(new JLabel("b")); labels.add(new JLabel("=")); JPanel controls = new JPanel(new GridLayout(0,1)); gui.add(controls, BorderLayout.CENTER); final JTextField a = new JTextField(10); controls.add(a); final JComboBox operand = new JComboBox(ops); controls.add(operand); final JTextField b = new JTextField(10); controls.add(b); final JTextField output = new JTextField(10); controls.add(output); ActionListener al = new ActionListener(){ public void actionPerformed(ActionEvent ae) { String expression = a.getText() + operand.getSelectedItem() + b.getText(); try { Object result = engine.eval(expression); if (result==null) { output.setText( "Output was 'null'" ); } else { output.setText( result.toString() ); } } catch(ScriptException se) { output.setText( se.getMessage() ); } } }; // do the calculation on event. operand.addActionListener(al); a.addActionListener(al); b.addActionListener(al); JOptionPane.showMessageDialog(null, gui); } } 

也可以看看

  • javax.script
  • ScriptEngine
  • 我的ScriptEngine演示。 用于探索JS引擎的function。

您将必须获取JComboBox的值并在Char上执行switch语句(因为无法switch字符串)以查看它是什么,然后执行正确的操作。

编辑:无法switch字符串….(Java 7)

 int c = compute(a,b, (String)comboBox.getSelectedItem()); 

 private int compute(int a, int b, String operator) { int result = 0; if("*".equals(operator)) result = a * b; else if("/".equals(operator)) result = a / b; else if("+".equals(operator)) result = a + b; else if("-".equals(operator)) result = a - b; else throw new IllegalArgumentException("operator type: " + operator + " ,not supported"); return result; 

}

这个类似的问题可以帮助。

或者,您可以将combobox中显示的每个运算符与自定义Calculator接口的实现相关联,该接口为您提供任意两个数字的结果。 就像是:

 interface Calculator { public int calculate(int a, int b); } class AddCalculator implements Calculator { public int calculate(int a, int b) {return a+b;} } 

关联可以是HashMap 。 接口Calculator可以作为参数传递的类型是通用的,并作为结果返回。 这将是我解决问题的方法,但我相信可能会有一个更简单的方法。