Results 1 to 4 of 4
  1. #1
    CGHMN is offline Member
    Join Date
    Jun 2011
    Rep Power

    Default Arithmetic expression calculator

    Hello everybody!
    ...hi dr nick

    Anyways I have this code that compiles but won't complete the actual function it serves I need to calculate expressions such as 2+3+9-4 then hit the calculate button then it is suppose to be displayed in the other field however I don't know where it it going wrong

    Java Code:
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
    import java.util.*;
    public class CalcExp extends JPanel 
       private JTextField jTextField1 = new JTextField(10);
       private JTextField jTextField2 = new JTextField(10); 
    	private JButton jButton1 = new JButton("Calculate");
    	public CalcExp()
    		jButton1.addActionListener(new ActionListener() {
    		public void actionPerformed(ActionEvent e) {
    		        // draw the interface
            Panel northP = new Panel();     // input
            Panel centerP = new Panel();    // controls
            Panel southP = new Panel();     // output
            // input panel
            northP.setLayout( new BorderLayout() );
            northP.add( "Center", jTextField1 = new JTextField(30) );
            // controls panel
            centerP.add( jButton1 = new JButton("Calculate") );
            // output panel
            southP.setLayout( new BorderLayout() );
            southP.add( "Center", jTextField2 = new JTextField(30) );
            jTextField2.setEditable( false );
            // add all the panels
            setLayout( new BorderLayout() );
            add( "North", northP );
            add( "Center", centerP );
            add( "South", southP );
    	 public boolean action( Event ev, Object arg )
            if ( instanceof JButton)
                if ("Calculate".equals(arg))
                return true;
            return false;
        // process the input string
        protected void process()
            // get the input string
            String inputString = jTextField1.getText();
            // trim the string
            inputString = inputString.trim();
            // ensure there are characters to process
            if (inputString.length() > 0)
                // check syntax, evaluate and display results if correct
                if ( checkSyntax() )
                    jTextField2.setText( " = " + evaluate() );
        // checkSyntax checks the syntax of the input string, calls reportError
        // to report any errors.  Returns true if the string is part of the
        // grammar, false if an error was found.
        protected boolean checkSyntax()
            int opCount = 1;        // start with a value
            boolean hasDec = false; // does the current # have a decimal component?
            int i;
            String inputString = jTextField1.getText();
            // check each character
            for (i = 0; i < inputString.length(); i++)
                    case '0':
                    case '1':
                    case '2':
                    case '3':
                    case '4':
                    case '5':
                    case '6':
                    case '7':
                    case '8':
                    case '9':
                        opCount = 0;
                    case '.':
                        if (((opCount += 2) > 2) || hasDec)
                            return reportError(i);
                        hasDec = true;
                    case '/':
                    case '*':
                        if (opCount++ > 0)
                            return reportError(i);
                        hasDec = false;
                    case '+':
                    case '-':
                        if (opCount++ > 1)
                            return reportError(i);
                        hasDec = false;
                        return reportError(i);
            // make sure expression ends with a value
            if (opCount > 0)
                return reportError(i);
                return true;
        // evaluate - returns the value obtained by evaluating the input expression
        protected double evaluate()
    	     String inputString = jTextField1.getText();
            // temp token handle
            String tok1, tok2;
            // create a string tokenizer object, keeping the delimiters as tokens
            StringTokenizer tokens = new StringTokenizer( inputString, "+-/*", true );
            // get the first token and put its value into result
            if ((tok1 = tokens.nextToken()).equals("+"))
                tok1 = tokens.nextToken();
            else if (tok1.equals("-"))
                tok1 = "-".concat(tokens.nextToken());
            double result = new Double(tok1).doubleValue();
            // evaluate the expression
            while (tokens.hasMoreTokens())
                // get the operator token
                tok1 = tokens.nextToken();
                // get the second operand token
                if ((tok2 = tokens.nextToken()).equals("+"))
                    tok2 = tokens.nextToken();
                else if (tok2.equals("-"))
                    tok2 = "-".concat(tokens.nextToken());
                // evaluate the subexpression
                switch (tok1.charAt(0))
                    case '+':
                        result += new Double(tok2).doubleValue();
                    case '-':
                        result -= new Double(tok2).doubleValue();
                    case '/':
                        result /= new Double(tok2).doubleValue();
                    case '*':
                        result *= new Double(tok2).doubleValue();
            return result;
        // reportError - Reports a syntax error to outputTA.  Always
        // returns false.
        protected boolean reportError( int index )
    	     String inputString = jTextField1.getText();
            // create a new string with the first line of output
            String outputString = new String("Syntax error:\n");
            // echo the user input as second line
            outputString = outputString.concat( inputString );
            outputString = outputString.concat( "\n" );
            // display pointer to error position as third line
            for (int i = 0; i < index; i++)
                outputString = outputString.concat(" ");
            outputString = outputString.concat("^");
            // copy the output string text to the output text area
            jTextField2.setText( outputString );
            return false;
    	 private static void createAndShowUI() {
          JFrame frame = new JFrame("M009");
          frame.getContentPane().add(new CalcExp());
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Madgaon, Goa, India
    Rep Power


    Posting inconsistently indented code with a whole lot of GUI stuff unrelated to the stated problem, and including a block of 10 commented-out lines in your post isn't the best way to get help on a forum.

    Recommended reading: SSCCE and How to ask questions the smart way


  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Voorschoten, the Netherlands
    Blog Entries
    Rep Power


    Basically it's the checkSyntax() method you're having problems with, all the rest doesn't matter here. You don't parse expressions like that. The easiest (read: less tricky) way to do that is to build a recursive descent parser; it follows the following grammar rules:

    Java Code:
    <expression> = <term> <expression_tail>
    <expression_tail> = empty | [+|-] <expression> <expression_tail>
    <term> = <factor> <term_tail>
    <term_tail>= empty | [*|/] <term> <term_tail>
    <factor> = - <factor> | <number> | ( <expression> )
    The stuff between angular brackets represent your (recursive) methods, all the rest are simple tokens. I left out the definition for a <number> for brevity. You also need a lexical analyzer that produces the simple tokens for the above parser. Google for "expression parser" and "recursive descent parser" for the details.

    kind regards,

    Build a wall around Donald Trump; I'll pay for it.

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Eastern Florida
    Rep Power


    it is suppose to be displayed in the other field however I don't know where it it going wrong
    Does it execute without exceptions?
    Can you explain what the code does and why that is not what you want it to do?
    Give the input sequence you use to test it and show what it outputs. Explain what is wrong with the output.

    Try debugging your code by adding lots of printlns to show the execution flow and the values of variables as they change.
    You should understand how you want your program to work. The printed output will show you where the code is executing differently from what you want it to do. When you see where that is happening you can go in and change that code so it works the way you want it to.

Similar Threads

  1. Find the value of the arithmetic expression...
    By hydride in forum Advanced Java
    Replies: 3
    Last Post: 03-16-2011, 10:17 AM
  2. Arithmetic using doubles
    By Black_Eye in forum New To Java
    Replies: 4
    Last Post: 10-19-2010, 09:35 AM
  3. Polynomials Arithmetic
    By thisisIT in forum New To Java
    Replies: 3
    Last Post: 03-09-2010, 02:27 PM
  4. String to Expression? calculator app question
    By Belbis in forum New To Java
    Replies: 2
    Last Post: 12-24-2008, 08:13 AM
  5. Arithmetic Stacks
    By unc123w in forum New To Java
    Replies: 22
    Last Post: 10-21-2008, 09:24 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts