Results 1 to 4 of 4
  1. #1
    clark_sandy is offline Member
    Join Date
    Jul 2008
    Posts
    2
    Rep Power
    0

    Default Calculator Problem. Thanks for helping! ^^

    greetings programmers. . can u help me with this project of mine?

    it needs a pemdas and mdas rule . but i dont know how to put it.

    can u please help me with this?

    i really appreciate ur help. thanks guys. .

    God bless


    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;

    public class MDAS {

    private String inputString = null;

    JLabel expression = new JLabel("Expression: ");
    JLabel result = new JLabel("Result: ");
    JTextField expression_textf = new JTextField(20);
    JTextField result_textf = new JTextField(10);


    JButton calculate = new JButton(" Calculate");
    JButton clear = new JButton(" Clear ");
    JButton cancel = new JButton (" Cancel ");

    //text functions
    public JPanel text_2() {


    JPanel Panel1 = new JPanel();
    JPanel Panel2 = new JPanel();

    Panel1.setLayout(new GridLayout(4,4));
    Panel1.add(expression);
    Panel1.add(expression_textf);
    Panel1.add(result);
    Panel1.add(result_textf);
    result_textf.setEnabled(false);
    result_textf.setFont(new Font("Comic Sans Ms", Font.PLAIN, 18));
    Panel2.setLayout(new FlowLayout(FlowLayout.RIGHT));
    Panel2.add(Panel1);

    return Panel2;

    }
    //Button functions
    public JPanel buttons_3(){

    clear.addActionListener ( new ActionListener () {
    public void actionPerformed (ActionEvent e) {

    clear();
    }
    });

    calculate.addActionListener ( new ActionListener () {
    public void actionPerformed (ActionEvent e) {

    process();
    }
    });
    cancel.addActionListener ( new ActionListener () {
    public void actionPerformed (ActionEvent e) {

    process();
    }
    });


    JPanel Panel1 = new JPanel();
    JPanel Panel2 = new JPanel();
    Panel1.setLayout(new GridLayout(5, 6));


    Panel2.add(calculate);
    Panel2.add(clear);
    Panel2.add(cancel);

    Panel2.setLayout(new FlowLayout(FlowLayout.RIGHT));
    Panel2.add(Panel1);

    return Panel2;


    }

    //Processing and display output
    protected void process()
    {
    // get the input string
    inputString = expression_textf.getText();

    // Out 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() )
    result_textf.setText( ""+ evaluate() );

    }

    protected boolean checkSyntax()
    {
    int opCount = 1; // Start with a value
    boolean hasDec = false; // Does the current # have a decimal component?
    int i;

    // Check each character
    for (i = 0; i < inputString.length(); i++)
    switch(inputString.charAt(i))
    {
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':

    opCount = 0;
    break;
    case '.':
    if (((opCount += 2) > 2) || hasDec)

    hasDec = true;
    break;
    case '%':
    case '/':
    case '*':
    if (opCount++ > 0)

    hasDec = false;
    break;
    case '%':
    case '+':
    case '-':
    if (opCount++ > 1)

    hasDec = false;
    break;
    default:
    return reportError(i);
    }

    // Make sure expression ends with a value

    return true;
    }

    protected double evaluate()
    {
    // 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());
    else if (tok1.equals("+"))
    tok1 = "-".concat(tokens.nextToken());
    else if (tok1.equals("-"))
    tok1 = "-".concat(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());
    else if (tok2.equals("+"))
    tok2 = "-".concat(tokens.nextToken());
    else if (tok2.equals("-"))
    tok2 = "-".concat(tokens.nextToken());
    else if (tok2.equals("%"))
    tok2 = "%".concat(tokens.nextToken());

    // Evaluate the subexpression
    switch (tok1.charAt(0))
    {
    case '+':
    result += new Double(tok2).doubleValue();
    break;
    case '-':
    result -= new Double(tok2).doubleValue();
    break;
    case '/':
    result /= new Double(tok2).doubleValue();
    break;
    case '*':
    result *= new Double(tok2).doubleValue();
    break;
    case '%':
    result %= new Double(tok2).doubleValue();
    break;
    }
    }
    return result;
    }
    public void clear() {

    expression_textf.setText("");
    result_textf.setText("");

    }
    protected boolean reportError( int index )
    {
    // create a new string with the first line of output
    String outputString = new String("Invalid Number\n");


    // copy the output string text to the output text area
    result_textf.setText( outputString );

    return false;
    }

    public JFrame buildNewFrame() {

    try{
    UIManager.setLookAndFeel(
    UIManager.getSystemLookAndFeelClassName());


    }catch(Exception e){}

    MDAS re = new MDAS();

    JPanel nPanel = new JPanel();
    JPanel sPanel = new JPanel();
    JPanel fPanel = new JPanel();

    nPanel = re.text_2 ();
    sPanel = re.buttons_3 ();


    fPanel.setLayout( new BorderLayout());
    fPanel.add(nPanel, BorderLayout.CENTER);
    fPanel.add(sPanel, BorderLayout.SOUTH);


    JFrame frame = new JFrame("MDAS");

    frame.setSize(50,50);
    frame.getContentPane().add(fPanel);

    frame.addWindowListener( new WindowAdapter() {

    public void windowClosing( WindowEvent e) {

    System.exit(0);
    }
    });

    return frame;

    }

    }


















    /// runner ///

    import javax.swing.JFrame;

    public class MDAS_Runner {

    public static void main(String args[]){

    JFrame run = new JFrame();
    MDAS rece = new MDAS ();
    run = rece.buildNewFrame();

    run.pack();
    run.setVisible(true);

    }

    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,589
    Rep Power
    23

    Default

    Could define: pemdas and mdas rule
    and how that relates to java programming?

  3. #3
    clark_sandy is offline Member
    Join Date
    Jul 2008
    Posts
    2
    Rep Power
    0

    Default ^^

    well. . i got the calculator working but its not following the mdas rule. u know wen i type 5-1*8-9 , the answer would be -12 by follwing the mdas rule. but in my calculator program, the result will be 23.

    Does anyone have any suggestions? thanks for the reply. .

    God bless

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,589
    Rep Power
    23

    Default

    What is the mdas rule?
    Does it relate to operator precedence?
    Your code will have to parse the expression and do the operations in the order of precedence. There are various methods for doing that. A simple one would be to scan the expression for the highest level operation, pick up its operands, do the operation and replace the operands and operation with the results and do it again until there are no operations left to do.
    It looks like your code is doing the operations from left to right.

Similar Threads

  1. Java Calculator
    By aapanju in forum New To Java
    Replies: 3
    Last Post: 04-17-2008, 05:33 AM
  2. Java calculator decimal
    By cart1443 in forum New To Java
    Replies: 2
    Last Post: 04-16-2008, 01:19 PM
  3. calculator not working
    By Renegade85 in forum New To Java
    Replies: 5
    Last Post: 03-10-2008, 03:27 PM
  4. Create a Calculator in Java
    By Albert in forum New To Java
    Replies: 2
    Last Post: 07-04-2007, 08:01 AM
  5. Swing Calculator
    By nemo in forum AWT / Swing
    Replies: 1
    Last Post: 05-28-2007, 11:07 AM

Posting Permissions

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