Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java计算器动作监听器;在文本字段中显示按钮_Java - Fatal编程技术网

Java计算器动作监听器;在文本字段中显示按钮

Java计算器动作监听器;在文本字段中显示按钮,java,Java,下面我有一个函数,可以对每次计算进行计算,但由于某种原因,我的数字在按下时不会出现在文本字段中,这意味着它不会将它们添加到字符串中。是否有任何明显的缺失会导致这种情况?当我运行时,我确实收到消息说输入错误。提前谢谢 private double eval(final String str) { class Parser { int pos = -1, c; void eatChar() { c = (++pos < str.

下面我有一个函数,可以对每次计算进行计算,但由于某种原因,我的数字在按下时不会出现在文本字段中,这意味着它不会将它们添加到字符串中。是否有任何明显的缺失会导致这种情况?当我运行时,我确实收到消息说输入错误。提前谢谢

private double eval(final String str) {
    class Parser {
        int pos = -1, c;

        void eatChar() {
            c = (++pos < str.length()) ? str.charAt(pos) : -1;
        }

        void eatSpace() {
            while (Character.isWhitespace(c)) eatChar();
        }

        double parse() {
            eatChar();
            double v = parseExpression();
            if (c != -1) throw new RuntimeException("Unexpected: " + (char)c);
            return v;
        }

        // Grammar:
        // expression = term | expression `+` term | expression `-` term
        // term = factor | term `*` factor | term `/` factor | term brackets
        // factor = brackets | number | factor `^` factor
        // brackets = `(` expression `)`

        double parseExpression() {
            double v = parseTerm();
            for (;;) {
                eatSpace();
                if (c == '+') { // addition
                    eatChar();
                    v += parseTerm();
                } else if (c == '-') { // subtraction
                    eatChar();
                    v -= parseTerm();
                } else {
                    return v;
                }
            }
        }

        double parseTerm() {
            double v = parseFactor();
            for (;;) {
                eatSpace();
                if (c == '/') { // division
                    eatChar();
                    v /= parseFactor();
                } else if (c == '*' || c == '(') { // multiplication
                    if (c == '*') eatChar();
                    v *= parseFactor();
                } else {
                    return v;
                }
            }
        }

        double parseFactor() {
            double v;
            boolean negate = false;
            eatSpace();
            if (c == '(') { // brackets
                eatChar();
                v = parseExpression();
                if (c == ')') eatChar();
            } else { // numbers
                if (c == '+' || c == '-') { // unary plus & minus
                    negate = c == '-';
                    eatChar();
                    eatSpace();
                }
                StringBuilder sb = new StringBuilder();
                while ((c >= '0' && c <= '9') || c == '.') {
                    sb.append((char)c);
                    eatChar();
                }
                if (sb.length() == 0) throw new RuntimeException("Unexpected: " + (char)c);
                v = Double.parseDouble(sb.toString());
            }
            eatSpace();
            if (c == '^') { // exponentiation
                eatChar();
                v = Math.pow(v, parseFactor());
            }
            if (negate) v = -v; // exponentiation has higher priority than unary minus: -3^2=-9
            return v;
        }
    }
    return new Parser().parse();
}

public void actionPerformed(ActionEvent e){
    String input = ((JButton)e.getSource()).getText();

    if(input.equals("C")){
        formula = "";
    }else if(input.equals("=")){
        try{
            double result = eval(formula);
            formula = "" + result;
        } catch(RuntimeException re){
            JOptionPane.showMessageDialog(null, "Wrong input: " + formula);
            formula = "";
        }
        }else{
            formula += input;
    }
        eqDisplay.setText(formula);
}

public static void main(String[] args) {
    Calculator calc = new Calculator();
}
}
更新:这里的布局也一样

public class Calculator extends JFrame implements ActionListener {  
String formula;
JTextField eqDisplay;

public Calculator() {
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(new Dimension(230, 250));
    this.setTitle("Calculator");
    this.setLayout(new BorderLayout());

    formula = "";

    JPanel centerPanel = new JPanel(new GridBagLayout());
    for (int i = 1; i <= 9; i++) {
        GridBagConstraints constraint = new GridBagConstraints();
        constraint.gridx = (i-1)%3;
        constraint.gridy = (i-1)/3;
        constraint.insets = new Insets(5, 5, 5, 5);
        JButton b = new JButton("" + i);
        centerPanel.add(b, constraint);
    }

    GridBagConstraints constraint = new GridBagConstraints();
    constraint.insets = new Insets(5, 5, 5, 5);

    constraint.gridx = 0;
    constraint.gridy = 3;
    constraint.gridwidth = 2;
    constraint.fill = GridBagConstraints.BOTH;
    JButton num_0 = new JButton("0");
    centerPanel.add(num_0, constraint);
    num_0.addActionListener(this);

    constraint.gridx = 2;
    constraint.gridy = 3;
    constraint.gridwidth = 1;
    constraint.fill = GridBagConstraints.NONE;
    JButton point = new JButton(".");
    centerPanel.add(point, constraint);
    point.addActionListener(this);

    constraint.gridx = 3;
    constraint.gridy = 0;       
    JButton divide = new JButton("/");
    centerPanel.add(divide, constraint);
    divide.addActionListener(this);

    constraint.gridx = 3;
    constraint.gridy = 1;       
    JButton multiply = new JButton("*");
    centerPanel.add(multiply, constraint);
    multiply.addActionListener(this);

    constraint.gridx = 3;
    constraint.gridy = 2;   
    JButton minus = new JButton("-");
    centerPanel.add(minus, constraint);
    minus.addActionListener(this);

    constraint.gridx = 3;
    constraint.gridy = 3;       
    JButton plus = new JButton("+");
    centerPanel.add(plus, constraint);
    plus.addActionListener(this);

    constraint.gridx = 0;
    constraint.gridy = 4;       
    constraint.gridwidth = 3;
    constraint.fill = GridBagConstraints.BOTH;

    JButton result = new JButton("=");
    centerPanel.add(result, constraint);
    result.addActionListener(this);

    constraint.gridx = 3;
    constraint.gridy = 4;       
    constraint.gridwidth = 1;
    constraint.fill = GridBagConstraints.NONE;

    JButton cButton= new JButton("C");
    centerPanel.add(cButton, constraint);
    cButton.addActionListener(this);

    this.add(centerPanel, BorderLayout.CENTER);
    JPanel northPanel = new JPanel(new FlowLayout());        
    eqDisplay = new JTextField(15);
    northPanel.add(eqDisplay);
    this.add(northPanel, BorderLayout.NORTH);

    this.setVisible(true);
}

您正在使用==比较actionPerformed方法中的字符串。如果您不确定为什么这是个坏主意,请检查我链接到的问题。不要使用==或!=比较字符串。使用相等的。。。或者EqualSignor案例。。。方法。了解==检查两个对象是否相同,这不是您感兴趣的。另一方面,方法检查两个字符串是否具有相同顺序的相同字符,这就是这里的问题。更改了。。。还是一样的问题。我理解为什么它不好,但我的教授在一个示例中编写了这段代码。不管怎样,它都应该是有效的,我一定是遗漏了什么。1我重新开始了这个问题。你的教授应该做不同的工作。对于一个人来说,在试图教别人如何编程时犯这样的初学者错误是不可接受的。3如果您想知道发生了什么,可以尝试使用调试器逐步完成此操作。您将能够准确地看到程序的哪些行正在运行,以响应每个可能的事件。问题出在我的布局中。当我使用循环创建按钮时,我并没有向每个按钮添加actionListener。感谢您的帮助: