假设我有整数变量a,b和c。
c = a + b; or c = a - b; or c = a / b; or c = a * b;
如您所见,计算运算符需要在运行时动态传递。所以我有一个jComboBox的运算符,所以用户将从jcomboBox中选择+, - ,*或/。
如何获取jCombobox selectedItem(可以是/,*, - 或+)并使用它来获取c的值。
EG。如果用户选择 *,那么表达式应为c = a * b 如果用户选择说 +,那么表达式应为c = a + b 。< / p>
答案 0 :(得分:4)
这是一种'欺骗'的方法。所有的解析都是由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
package ScriptEngine
ScriptEngine
demo.用于探索JS引擎的功能。答案 1 :(得分:2)
您必须获取JComboBox
的值并对Char执行switch
语句(因为字符串上不能switch
)以查看它是什么,然后执行正确的操作。
编辑:字符串上的switch
....(Java 7)
答案 2 :(得分:2)
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;
}
答案 3 :(得分:1)
This similar question可以提供帮助。
或者,您可以将组合框中显示的每个运算符与自定义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<String, Calculator>
的形式。接口Calculator
可以作为参数传递的类型是通用的,并作为结果返回。这将是我解决问题的方法,但我相信可能会有一个更简单的问题。