how to compute the result of two integer values but get the additive or multiplicative operator from a jComboBox in java

a 夏天 提交于 2019-12-18 09:36:55

问题


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.


回答1:


Here is a way to 'cheat'. All the parsing is done by the ScriptEngine, we just need to assemble the parts of the expression.

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);
    }
}

See Also

  • The javax.script package
  • The ScriptEngine
  • My ScriptEngine demo. for exploring the capabilities of the JS engine.



回答2:


You will have to get the Value of the JComboBox and do a switch statement on the Char (because cant switch on a string) to see which it is, then perform the correct operation.

Edit: Cant switch on a string.... yet (Java 7)




回答3:


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;

}




回答4:


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:

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

The association can be of a form of HashMap<String, Calculator>. The interface Calculator 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.



来源:https://stackoverflow.com/questions/6425953/how-to-compute-the-result-of-two-integer-values-but-get-the-additive-or-multipli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!