【问题标题】:Attempting to write code for a simple calculator. Trouble getting the program to solve the equation that the user inputs试图为一个简单的计算器编写代码。无法让程序求解用户输入的方程
【发布时间】:2015-05-31 01:48:48
【问题描述】:

目前,当用户按下计算器上的按钮时,它会在上面的文本框中显示值,但我无法用它来求解方程。按下的每个按钮都显示在 TextField 中,但是当我按下“=”(等于)时,我希望它能够解决等式。你能帮我解决这个问题吗?

//Michael Moradi
//Period C1
//June 2, 2015
//Final Project Semester 2

import javax.swing.*; //imports all that is needed for the code

import java.awt.*;
import java.awt.event.*;

public class Calculator extends JFrame implements ActionListener {

    public JButton button1, button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12, button13, button14, button15, button16;
    public JTextArea text; //makes these accessible throughout the code

    public Calculator()
    {
        setSize(350,300); //sets size to 300 by 300
        setResizable(false); //does not let user change the size of the window
        setDefaultCloseOperation(EXIT_ON_CLOSE);//makes app close when I press the x on the top left

        Container contentPane = getContentPane();//gets the contentPane
        contentPane.setBackground(Color.CYAN);//sets background color to white         

        contentPane.setLayout(new FlowLayout());//makes the contentPane read from left to right

        text = new JTextArea(1, 25);
        contentPane.add(text);
        text.setEditable(false);

        button1 = new JButton ("7");
        contentPane.add(button1);
        button1.addActionListener(this);

        button2 = new JButton ("8");
        contentPane.add(button2);
        button2.addActionListener(this);

        button3 = new JButton ("9");
        contentPane.add(button3);
        button3.addActionListener(this);

        button4 = new JButton ("÷");
        contentPane.add(button4);
        button4.addActionListener(this);

        button5 = new JButton ("4");
        contentPane.add(button5);
        button5.addActionListener(this);

        button6 = new JButton ("5");
        contentPane.add(button6);
        button6.addActionListener(this);

        button7 = new JButton ("6");
        contentPane.add(button7);
        button7.addActionListener(this);

        button8 = new JButton ("x");
        contentPane.add(button8);
        button8.addActionListener(this);

        button9 = new JButton ("1");
        contentPane.add(button9);
        button9.addActionListener(this);

        button10 = new JButton ("2");
        contentPane.add(button10);
        button10.addActionListener(this);

        button11 = new JButton ("3");
        contentPane.add(button11);
        button11.addActionListener(this);

        button12 = new JButton ("-");
        contentPane.add(button12);
        button12.addActionListener(this);

        button13 = new JButton ("0");
        contentPane.add(button13);
        button13.addActionListener(this);

        button14 = new JButton ("C");
        contentPane.add(button14);
        button14.addActionListener(this);

        button15 = new JButton ("=");
        contentPane.add(button15);
        button15.addActionListener(this);

        button16 = new JButton ("+");
        contentPane.add(button16);
        button16.addActionListener(this);



    }

    public static void main(String[] args)
    {
        Calculator guiWindow = new Calculator(); //uses GUI
        guiWindow.setVisible(true); //makes it visible

    }

    public void actionPerformed(ActionEvent e)
    {
        Container contentPane = getContentPane();

        String enteredNumbers = text.getText();

        if (e.getActionCommand().equals("7"))
        text.setText(enteredNumbers + ("7"));

        if (e.getActionCommand().equals("8"))
        text.setText(enteredNumbers + ("8"));

        if (e.getActionCommand().equals("9"))
        text.setText(enteredNumbers + ("9"));

        if (e.getActionCommand().equals("÷"))
        text.setText(enteredNumbers + ("÷"));

        if (e.getActionCommand().equals("4"))
        text.setText(enteredNumbers + ("4"));

        if (e.getActionCommand().equals("5"))
        text.setText(enteredNumbers + ("5"));

        if (e.getActionCommand().equals("6"))
        text.setText(enteredNumbers + ("6"));

        if (e.getActionCommand().equals("x"))
        text.setText(enteredNumbers + ("x"));

        if (e.getActionCommand().equals("1"))
        text.setText(enteredNumbers + ("1"));

        if (e.getActionCommand().equals("2"))
        text.setText(enteredNumbers + ("2"));

        if (e.getActionCommand().equals("3"))
        text.setText(enteredNumbers + ("3"));

        if (e.getActionCommand().equals("-"))
        text.setText(enteredNumbers + ("-"));

        if (e.getActionCommand().equals("0"))
        text.setText(enteredNumbers + ("0"));

        if (e.getActionCommand().equals("C"))
        text.setText("");

        if (e.getActionCommand().equals("="))
        text.setText(enteredNumbers + ("="));

        if (e.getActionCommand().equals("+"))
        text.setText(enteredNumbers + ("+"));




    }

}

【问题讨论】:

  • 可能只是我,但看起来您的代码仅在按下 = 按钮时设置文本。你有任何关于方程求解的代码吗?
  • 另见calculator example。它使用ScriptEngine 来评估文本字段中的表达式。
  • 一个计算是{value}{operator}{value}的一组,需要生成这些组并进行计算,别忘了,优先顺序
  • 顺便说一句,text = new JTextArea(1, 25); 最好是text = new JTextField(25);(在text 字段的声明中进行适当的更改)。
  • String#split 可能是我的第一个停靠港

标签: java swing calculator


【解决方案1】:

对于这样的事情,您只需更改您的ActionListener。顺便说一下,我强烈建议您提供更有意义的名称的所有其他按钮只是将文本标记添加到计算器字段。根据您的描述,“=”的意思是解决它。所以,

if (e.getActionCommand().equals("="))
    text.setText(enteredNumbers + ("="));

应该更像这样:

if (e.getActionCommand().equals("=")) {
    String math = text.getText();
    answerField.setText(solve(math));
}

private solve(String math) {
    //This is the tricky part, see description next.
}

对于您的解决方法,我会建议两件事之一。第一个是用一系列regular expressions 分解它,您可以创建并尝试(在实施之前)here。从那里,您将知道提供的字段是数字还是运算符。运算符通常最好与枚举和Function 字段配对。不幸的是,这仍然留下了如何处理运算符优先级的问题。

为此,您需要将其分解为Reverse Polish Notation;类似于Shunting-Yard algorithm。之后,您就可以按出现的顺序单步执行每个操作函数。

如果您赶时间,您可能还可以使用 Java 脚本引擎并将您的数学简单地实现为可解的 JavaScript;可用的教程here。目前,Javascript/ECMAscript 是可用的,但我相信还有很多其他的可以通过外部库获得。 (当您处理频繁更改的动态代码时,这是天赐之物。)

希望这些资源之一对您有所帮助。实际上,我曾经使用第一种方法在 Java 中实现了一个专门用于求解数学方程的脚本;现在只需使用第二种方法将其插入新应用程序即可。祝你好运!

【讨论】:

    【解决方案2】:

    这样的事情怎么样,通过 Java 脚本引擎使用 JavaScript 库 math.js。您可以从以下位置下载文件 math.js:http://mathjs.org/download.html

    package org.mathjs;
    
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    
    public class MathJS {
        protected static String MATHJS_SCRIPT = "./lib/mathjs/math.js";
        protected ScriptEngine engine;
    
        public MathJS () throws FileNotFoundException, ScriptException {
            ScriptEngineManager manager = new ScriptEngineManager ();
            engine = manager.getEngineByName ("js");
    
            engine.eval(new FileReader(MATHJS_SCRIPT));
            engine.eval("var parser = math.parser();");
            engine.eval("var precision = 14;");
        }
    
        public String eval (String expr) throws ScriptException {
            String script = "math.format(parser.eval('" + expr + "'), precision);";
            return (String) engine.eval(script);
        }
    
        public static void main(String[] args) 
                throws FileNotFoundException, ScriptException {
            MathJS math = new MathJS();
            System.out.println(math.eval("a = 4.5"));
            System.out.println(math.eval("1.2 * (2 + a)"));
            System.out.println(math.eval("5.08 cm in inch"));
            System.out.println(math.eval("sin(45 deg) ^ 2"));   
            System.out.println(math.eval("9 / 3 + 2i") );   
            System.out.println(math.eval("det([-1, 2; 3, 1])"));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-21
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多