如何计算两个整数值的结果,但从java中的jComboBox获取加法或乘法运算符

发布于 2024-11-16 06:07:15 字数 350 浏览 5 评论 0原文

假设我有整数变量 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

逆夏时光 2024-11-23 06:07:15

这里有一个“作弊”的方法。所有的解析都是由ScriptEngine完成的,我们只需要组装表达式的各个部分即可。

ScriptEngine Calculator

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
  • 我的 < a href="http://pscode.org/jse.html" rel="nofollow noreferrer">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.

ScriptEngine Calculator

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

℉服软 2024-11-23 06:07:15

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

编辑:还不能switch字符串......(Java 7)

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)

得不到的就毁灭 2024-11-23 06:07:15
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;

}

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;

}

可遇━不可求 2024-11-23 06:07:15

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

或者,您可以将组合框中显示的每个运算符与自定义计算器接口的实现相关联,该接口可以为您提供任意两个数字的结果。类似于:

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 可以对作为参数传递并作为结果返回的类型进行通用。这就是我解决问题的方法,但我确信可能有更简单的方法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文