当前位置: 首页 > 知识库问答 >
问题:

如何为一个简单的计算器解决一个计算的字符串版本?[副本]

麹耘豪
2023-03-14

这是一个简单的计算器,用户可以键入计算并点击Enter,计算器将确定它是否是有效的计算。如果是有效计算,则进行计算。如果不是,则将错误消息写入屏幕。

计算已执行部分未完成。

是否有人建议getAnswer()方法的解决方案。

不胜感激。

null

import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;


@SuppressWarnings("serial")
public class Calculator extends JFrame{

    private interface CalculatorInterface {
        public void writeToScreen(String text);
        public void clearScreen();
        public String getScreenText();  
    }

    private class CalculatorPanel extends JPanel implements CalculatorInterface {

        private class NumberPanel extends JPanel implements CalculatorInterface {

            private static final int NUMTOTAL = 10;

            private CalculatorPanel calcPanel;
            private JButton[] numButtons;

            public NumberPanel(CalculatorPanel calcPanel) {
                this.calcPanel = calcPanel;
                buildLayout();
                addButtons();
            }
            private void buildLayout() {
                this.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

                GridLayout layout = new GridLayout(4,3);
                layout.setHgap(1);
                layout.setVgap(1);

                this.setLayout(new GridLayout(4,3));

            }
            private void addButtons() {
                numButtons = new JButton[NUMTOTAL];

                for(int i = numButtons.length -1; i >= 0 ; i--) {
                    numButtons[i] = new JButton("" + i);
                    numButtons[i].setPreferredSize(new Dimension(60,40));
                    numButtons[i].setFont(new Font("Sans serif", Font.PLAIN, 18));
                    numButtons[i].addActionListener(
                            new ActionListener() {
                                @Override
                                public void actionPerformed(ActionEvent e) {
                                    String text = ((JButton)e.getSource()).getText().trim();
                                    if(getScreenText().equals("Invalid Calc")) {
                                        clearScreen();
                                        writeToScreen(text);
                                    }else {
                                        writeToScreen(text);
                                    }       
                                }
                            });
                    this.add(numButtons[i]);
                }
            }
            @Override
            public void writeToScreen(String text) {
                calcPanel.writeToScreen(text);
            }
            @Override
            public void clearScreen() {
                calcPanel.clearScreen();

            }
            @Override
            public String getScreenText() {
                return calcPanel.getScreenText();
            }

        }

        private class OperPanel extends JPanel implements CalculatorInterface {

            private static final int ADD = 0;
            private static final int SUB = 1;
            private static final int MULT = 2;
            private static final int DIV = 3;
            private static final int OPENB = 4;
            private static final int CLOSEB = 5;
            private static final int CLEAR = 6;
            private static final int EQL = 7;


            private static final int OPERTOTAL = 8;

            private CalculatorPanel calcPanel;
            private JButton[] operButtons;

            public OperPanel(CalculatorPanel calcPanel) {
                this.calcPanel = calcPanel;
                buildLayout();
                addButtons();
            }

            private void buildLayout() {
                GridLayout layout = new GridLayout(4,1);
                layout.setHgap(1);
                layout.setVgap(1);

                this.setLayout(new GridLayout(4,1));
            }

            private void addButtons() {
                operButtons = new JButton[OPERTOTAL];

                operButtons[ADD] = makeButton(ADD, "+");
                operButtons[SUB] = makeButton(SUB, "-");
                operButtons[MULT] = makeButton(MULT, "*");
                operButtons[DIV] = makeButton(DIV, "/");
                operButtons[CLEAR] = makeButton(CLEAR, "CL");
                operButtons[EQL] = makeButton(EQL, "=");
                operButtons[OPENB] = makeButton(OPENB, "(");
                operButtons[CLOSEB] = makeButton(CLOSEB, ")");

                for(JButton button: operButtons) {
                    this.add(button);
                }   
            }

            private JButton makeButton(int index, String label) {   

                operButtons[index] = new JButton(label);
                operButtons[index].addActionListener(
                        new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent e) {
                                String text = ((JButton)e.getSource()).getText();
                                if(text.equals("=")) {
                                    String screenText = getScreenText();
                                    clearScreen();
                                    try {
                                        writeToScreen(getAnswer(screenText));
                                    }catch(Exception excep) {
                                        writeToScreen("Invalid Calc");
                                    }
                                }else if(text.equals("CL")) {
                                    clearScreen();  
                                }else {
                                    writeToScreen(text);
                                }
                            }       
                        });

                return operButtons[index];      
            }


            private String getAnswer(String text) throws Exception {
                /*I'm trying to solve for any input by the user e.g
                 *(the stuff in square brackets represents what is displayed
                 * on the screen:.
                 *[1+1] (hits equals) [2]
                 *[1+2-3] (hits equals) [0]
                 *[1+2*3] (hits equals) [7]
                 *[10*(14+1/2)] (hits equals) [145]
                 */
                throw new Exception();
            }
            @Override
            public String getScreenText() {
                return calcPanel.getScreenText();
            }

            @Override
            public void clearScreen() {
                calcPanel.clearScreen();

            }

            @Override
            public void writeToScreen(String text) {
                calcPanel.writeToScreen(text);

            }

        }


        private NumberPanel numPanel;

        private OperPanel operPanel;
        private JTextField calcScreen;

        public CalculatorPanel(JTextField calcScreen) {
            this.calcScreen = calcScreen;

            buildNumPanel();
            buildOperPanel();

            buildCalcPanel();


        }
        private void buildNumPanel() {
            this.numPanel = new NumberPanel(this);
        }

        private void buildOperPanel() {
            this.operPanel = new OperPanel(this);
        }

        private void buildCalcPanel() {
            this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
            this.add(numPanel);
            this.add(operPanel);
        }


        @Override
        public void writeToScreen(String text) {
            calcScreen.setText(getScreenText() + text);     
        }

        @Override
        public String getScreenText() {
            return calcScreen.getText();
        }

        @Override
        public void clearScreen() {
            calcScreen.setText("");
        }
    }

    private JPanel mainPanel;
    private JTextField calcScreen;

    private CalculatorPanel calcPanel;
    public Calculator() {
        buildScreen();

        buildCalcPanel();

        buildMainPanel();

        buildCalculator();
    }

    private void buildScreen() {
        this.calcScreen = new JTextField();
        this.calcScreen.setPreferredSize(new Dimension(150,50));
        this.calcScreen.setHorizontalAlignment(JTextField.CENTER);
        this.calcScreen.setFont(new Font("Sans serif", Font.PLAIN, 30));

    }

    private void buildCalcPanel() {
        this.calcPanel = new CalculatorPanel(this.calcScreen);
    }

    private void buildMainPanel() {
        this.mainPanel = new JPanel();
        this.mainPanel.setBorder(new EmptyBorder(10,10,10,10));
        this.mainPanel.setLayout(new BoxLayout(this.mainPanel, BoxLayout.Y_AXIS));

        this.mainPanel.add(calcScreen);
        this.mainPanel.add(calcPanel);
    }

    private void buildCalculator() {

        this.add(mainPanel);
        this.setTitle("Calculator");
        this.pack();        
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        @SuppressWarnings("unused")
        Calculator calc = new Calculator();
    }

}

如何检查一个字符串是否是一个简单计算器的有效计算?

编辑1:修正了makeButton()方法中的一个愚蠢的错误,如果我传递的是要验证的按钮的文本,而不是屏幕上的文本。(我是个白痴。)

编辑2:从代码中删除isValid(字符串文本),使其成为getAnswer()方法在输入不是有效计算时抛出异常。

共有1个答案

郑西岭
2023-03-14

正如前面的StackOverflow答案(计算以字符串形式给出的数学表达式)中提到的,您可以使用JavaScriptScriptEngine根据从文本字段检索的字符串计算表达式。首先将其放置在try-catch block中,以查看表达式中是否存在错误。在catch块中,将存储其是否为有效表达式的变量设置为false。

boolean validExpression = true;

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String input = textField.getText() // Modify this to whatever variable you have assigned to your text field

try {
    System.out.println(engine.eval(foo));
} 
catch (ScriptException e) {
    validExpression = false;
    System.out.println("Invalid Expression");
}

确保包含以下导入:

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

虽然您可以尝试实现分流场算法或其他算术解析器,但这只是一种更实用的解决方案。

 类似资料:
  • 本文向大家介绍一个简单的jQuery计算器实现了连续计算功能,包括了一个简单的jQuery计算器实现了连续计算功能的使用技巧和注意事项,需要的朋友参考一下 一个简单的jQuery计算器,只是实现了一个连续计算的功能

  • 问题内容: 我是Java字符串的新手,问题是我想计算字符串中特定单词的出现次数。假设我的字符串是: 现在,我也不想拆分它,所以我想搜索一个“雄猫”这个词。它在我的字符串中出现了两次! 我正在尝试的是: 它给了我46个计数器的价值!那么解决方案是什么? 问题答案: 您可以使用以下代码: 演示版 它匹配。 表示在找到匹配项时执行循环内给出的任何操作。并且我将by 的值递增,因此很显然,这给出了一个字符

  • 我无法激活计数器++。到目前为止,s2能够读取s1,但不能计数出现的次数。如有任何帮助,我们将不胜感激。(我意识到我在错误的字符串中工作,但它帮助我首先在这里创建解决方案,然后将其发送到第二个字符串,这是不是很糟糕的逻辑?) 很抱歉问了这个愚蠢的问题,我对编程很陌生 //我需要一个扫描器来读取我所写内容,该扫描器应该计算一个字符的出现次数另一个扫描器声明的扫描器a会询问“write Somethi

  • 问题内容: 在Java中如何计算一个字符串表达式?,例如:”3+2” 问题答案: 使用JDK1.6,您可以使用内置的Javascript引擎。

  • 我试图计算所有colu_a值的所有实例 对于ex. 有没有一行代码可以告诉我每个值(A,B,C,D)在该列中存在多少次?

  • 问题内容: 我在Sqlite中有一个查询,其中涉及复杂的列计算,可以这样说: 我想将此计算选择为,但我还需要将其用作另一种计算的组成部分: 不幸的是,这会产生错误: 我知道我可以简单地重复计算: 但是,假设操作复杂且昂贵,是否有什么方法可以在以后重新引用它而不必重新计算呢? 问题答案: 您需要使用子查询。 结果