从JTextField计算方程式

时间:2016-01-25 10:44:33

标签: java calculator

我有一个问题: 我需要为学校建立一个计算器,我需要在JTextField中输入完整的等式(例如7 * 6 * 3 + 1-12),并且需要计算完整的等式,并且遵循*的规则。 +。 有没有办法做到这一点?

/**
 Case : Computer Science Corporation
 */
import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CSC extends JFrame {
    // frame settings//
    public static void main(String args[] ) {
        JFrame frame = new CSC();
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Rekenmachine ");
        JPanel Paneel = new Paneel();
        frame.setContentPane( new Paneel() );
        frame.setVisible(true);
    }
}
//paneel opbouw//
class Paneel extends JPanel{
    public JButton Een,Twee,Drie,Vier,Vijf,Zes,Zeven,Acht,Negen,Nul,C,Min,Plus,Deel,Vermenigvuldig,Totaal,LOGO;
    public JTextField Output;

    public Paneel(){
        setLayout (null);

        Een = new JButton("1");
        Een.setBounds(20, 225, 50, 50);
        Een.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "1");

            }

        });

        Twee = new JButton("2");
        Twee.setBounds(80, 225, 50, 50);
        Twee.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "2");
            }

        });

        Drie = new JButton("3");
        Drie.setBounds(140, 225, 50, 50);
        Drie.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "3");
            }

        });

        Vier = new JButton("4");
        Vier.setBounds(20, 165, 50, 50);
        Vier.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "4");
            }

        });

        Vijf = new JButton("5");
        Vijf.setBounds(80, 165, 50, 50);
        Vijf.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "5");
            }

        });

        Zes = new JButton("6");
        Zes.setBounds(140, 165, 50, 50);
        Zes.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "6");
            }

        });

        Zeven = new JButton("7");
        Zeven.setBounds(20, 105, 50, 50);
        Zeven.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "7");
            }

        });

        Acht = new JButton("8");
        Acht.setBounds(80, 105, 50, 50);
        Acht.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "8");
            }

        });

        Negen = new JButton("9");
        Negen.setBounds(140, 105, 50, 50);
        Negen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "9");
            }

        });

        Nul = new JButton("0");
        Nul.setBounds(20, 285, 50, 50);
        Nul.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "0");
            }

        });

        C = new JButton("C");
        C.setBounds(80, 285, 50, 50);
        C.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText ("");
            }

        });

        Min = new JButton("-");
        Min.setBounds(200, 285, 50, 50);
        Min.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText ("");
            }

        });

        Plus = new JButton("+");
        Plus.setBounds(200, 225, 50, 50);
        Plus.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "+");
            }

        });

        Deel = new JButton("/");
        Deel.setBounds(200, 105, 50, 50);
        Deel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "/");
            }

        });

        Vermenigvuldig = new JButton("*");
        Vermenigvuldig.setBounds(200, 165, 50, 50);
        Vermenigvuldig.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Output.setText (Output.getText() + "*");
            }

        });

        Totaal = new JButton("=");
        Totaal.setBounds(140, 285, 50, 50);


        Output = new JTextField("");
        Output.setBounds(20, 20, 230, 75);
        Output.setEditable(false);
        Output.setHorizontalAlignment(SwingConstants.RIGHT);

        LOGO = new JButton ("LOGO");
        LOGO.setBounds (20,345,230,75);


        add (Een);
        add (Twee);
        add (Drie);
        add (Vier);
        add (Vijf);
        add (Zes);
        add (Zeven);
        add (Acht);
        add (Negen);
        add (Nul);
        add (C);
        add (Min);
        add (Plus);
        add (Vermenigvuldig);
        add (Totaal);
        add (Deel);
        add (Output);
        add (LOGO);
    }
} 

如果您需要更多信息,请告诉我们。

-

-

更新

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
    Totaal = new JButton("=");
            Totaal.setBounds(140, 285, 50, 50);
            Totaal.addActionListener (new ActionListener(){
                public void actionPerformed (ActionEvent e)  {
                    String expression = "Output.getText";
                    // Get JavaScript engine
                    ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
                    try {
                    // Evaluate the expression
                    Object result = engine.eval(expression);
                    System.out.println(expression + " = " + result);
                }
                    catch (ScriptException a) {
                    // Something went wrong
                    a.printStackTrace();
            }
        }
    });

当我编译它时说“过程完成” 但是当我输入一个等式时,我得到以下错误:

--------------------Configuration: CSC - JDK version 1.8.0_51 <Default> - <Default>--------------------
javax.script.ScriptException: ReferenceError: "Output" is not defined in <eval> at line number 1
    at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:455)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:439)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:401)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:397)
    at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:152)
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
    at Paneel$16.actionPerformed(CSC.java:179)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6525)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6290)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4881)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: <eval>:1 ReferenceError: "Output" is not defined
    at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:319)
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:291)
    at jdk.nashorn.internal.objects.Global.__noSuchProperty__(Global.java:914)
    at jdk.nashorn.internal.scripts.Script$\^eval\_.:program(<eval>:1)
    at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:636)
    at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:229)
    at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:387)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:437)
    ... 41 more

3 个答案:

答案 0 :(得分:2)

导入这些

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
你的函数中的

就是这样写的

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
//value from jTextField is output.getText();
//value may be "56+5" or "56/4+2" etc..
    System.out.println(engine.eval(output.getText()))

答案 1 :(得分:0)

有许多方法可以实现这一点,有些方法比其他方法更好,更有效。

正如您所做的那样,您可以获得等式的文本,如下所示:

output.getText();

然后,使用这个等式,您可以继续使用自己的算法计算答案,尽管这可能会很困难,效率低下并且您将面临许多问题。

我建议你研究使用堆栈和计算器,因为这将是一个很好的实现它的方法,特别是RPN(反向波兰表示法),因为我认为这很容易理解并且工作得很好。

正如Andy所提到的那样,调车码算法也是一个很好的算法。

答案 2 :(得分:0)

如果我是你,我会优雅地使用反向波兰符号(https://en.wikipedia.org/wiki/Reverse_Polish_notation)。

初学者看起来有点复杂,但学习也很有意义。