User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Java section within the Software Development category of DaniWeb, a massive community of 391,558 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,753 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Java advertiser: Lunarpages Java Web Hosting
Views: 2039 | Replies: 2
Reply
Join Date: Nov 2006
Posts: 39
Reputation: nnobakht is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 1
nnobakht nnobakht is offline Offline
Light Poster

Java Simple calc

  #1  
Mar 23rd, 2007
hey guys im supposed to write a simple calculator in java. Not in applet. Stack class has already been given and i was supposed to tokenize the input, have a function convert to take it from infix to postfix notation and eval to evaluate it. i have written the code convert but when i try to write the eval code i always get errors any idea how to start the eval function. my code is posted below

import java.util.*;
import java.math.*;
import java.io.*;

public class Tokens{

    private int position=0;    //Postion  to put in array. Increases as the String is tokenized.
    private String [] Tokenized= new String[500];    //Tokenized version of array
    private Stack operand = new Stack();  //Operand Stack for conversion
    private static Stack output=new Stack(); //Output Stack for conversion. (Everything will be in here at end of conversion)
    public Tokens()
    /********************************
    *Start of tokenize class. Once called it will use the Parse function
    *to tokenize the given String (ie. user input)*/
    {
        System.out.println("2+4-(5*3)^2^3+3");
        Parse("2+4-(5*3)**2**3+3" + " ");
        convert(Tokenized);
    }

    public void Parse(String s){
        /****************************
        *Parse Function. Takes Input as string and tokenizes it to be able to use as a Token.
        ****************************/
        String temp=""; //Digits and operands are temporarily stored, seperatly in here.
        for (int i=0; i<s.length();i++){
            if(Character.isDigit(s.charAt(i))){
                temp+=s.substring(i,i+1);
            }
            else
            {
                if(temp != "")
                {
                    Tokenized[position]=temp;
                    position++;
                }
                temp="";
                switch (s.charAt(i)){
                    case '+':
                        temp="+";
                        break;
                    case '-':
                        temp="-";
                        break;
                    case '(':
                        temp="(";
                        break;
                    case ')':
                        temp=")";
                        break;
                    case '/':
                        temp="/";
                        break;
                    case '*':
                        if (s.charAt(i+1) == '*')
                        {
                            temp="^";
                            i++;
                        }
                        else{
                            temp="*";
                        }
                        break;
                    case ' ':
                        break;
                    default:
                        System.out.println("Incorrect format.");
                }
                if(temp != "")
                {
                    Tokenized[position]=temp;
                    position++;
                }
                temp = "";
            }
        }
    }



    public int evaluate(String x){
        /*************************
        Evaluates the given sign.
        * +, - have same value:1
        * *, / have same value:2
        * ^ has value of: 3
        * otherwise it is value: 0
        *************************/
        if(x.equals("+") )
        {
            return 1;
        }
        else if(x.equals("-"))
        {
            return 1;
        }
        else if(x.equals("*"))
        {
            return 2;
        }
        else if (x.equals("/"))
        {
            return 2;
        }
        else if(x.equals("^"))
        {
            return 3;
        }
        else
        {
            return 0;
        }

    }
    public void Bracket()
    {
        String temp=((String)(operand.peek()));
        while(!((String)(operand.peek())).equals("("))
        {
            output.push(operand.pop());
        }
        operand.pop();
    }
    public void convert(String[] Tokenized){
        /****************************************************
        *takes the token created in Parse function and
        *converts it from Infix notation to postfix notion
        *Uses evaluate function to see what to do with signs
        * and puts it in 2 stacks operand and output
        *untill the end. at the end everything is in
        *stack output which will be returned
        ****************************************************/
        for (int j=0; j<position; j++)
        {
            if (Character.isDigit(Tokenized[j].charAt(0)))
            {
                output.push(Tokenized[j]);
            }
            else
            {

                if (!Tokenized[j].equals("("))
                {
                        if (operand.empty())
                        {
                            operand.push(Tokenized[j]);
                        }
                        else if (((String)(operand.peek())).equals("("))
                        {
                            operand.push(Tokenized[j]);
                        }
                        else if (Tokenized[j].equals(")"))
                        {
                            Bracket();
                        }
                        else if (Tokenized[j].equals("^"))
                        {
                            if (((String)(operand.peek())).equals("^"))
                            {
                                operand.push(Tokenized[j]);
                            }
                            else
                            {
                                int second=evaluate((String)(operand.peek()));
                                int first=evaluate(Tokenized[j]);
                                if (first > second)
                                {
                                    operand.push(Tokenized[j]);
                                }
                                else if (first == second)
                                {
                                    output.push(operand.pop());
                                    operand.push(Tokenized[j]);
                                }
                                else if (first < second)
                                {
                                output.push(operand.pop());
                                operand.push(Tokenized[j]);
                                }
                            }
                        }
                        else
                        {
                            int second=evaluate((String)(operand.peek()));
                            int first=evaluate(Tokenized[j]);
                            if (first > second)
                            {
                                operand.push(Tokenized[j]);
                            }
                            else if (first == second)
                            {
                                output.push(operand.pop());
                                operand.push(Tokenized[j]);
                            }
                            else if (first < second)
                            {
                                output.push(operand.pop());
                                operand.push(Tokenized[j]);
                            }
                        }
                }
                else if (Tokenized[j].equals("("))
                {
                    operand.push(Tokenized[j]);
                }
            }
        }
        while(!operand.empty())
        {
            output.push(operand.pop());
        }

    }


    public static void main(String[] args){
        Tokens app = new Tokens();
    }
} 
AddThis Social Bookmark Button
Reply With Quote  
Join Date: Nov 2006
Posts: 39
Reputation: nnobakht is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 1
nnobakht nnobakht is offline Offline
Light Poster

Re: Java Simple calc

  #2  
Mar 23rd, 2007
k guys i got somewhat how to do the eval but does someone mind looking at the parse function for me. it is supposed to tokenize a string that is written for a calc such as 3+4/(5+1) but it will not take the last entry unless i add a space " " to it. any1 have a fix for it? my program runs fine like it is but it is because i manipulated it to. any ideas?
Reply With Quote  
Join Date: Aug 2005
Posts: 4,663
Reputation: iamthwee is just really nice iamthwee is just really nice iamthwee is just really nice iamthwee is just really nice 
Rep Power: 16
Solved Threads: 297
iamthwee's Avatar
iamthwee iamthwee is offline Offline
Industrious Poster

Re: Java Simple calc

  #3  
Mar 24th, 2007
>2+4-(5*3)**2**3+3"

That is not a valid expression. Personally I'd chop that double ** out.

2+4-(5*3)^2^3+3

After conversion from infix to postfix, would be:-

2 4 + 5 3 * 2 2 ^ ^ - 3 +


Thus working from left to right...

2 4 + 5 3 * 2 2 ^ ^ - 3 +

2 + 4 = 6 {pop}

6 5 3 * 2 2 ^ ^ - 3 +

5 * 3 = 15 {pop}

6 15 2 2 ^ ^ - 3 +

2 ^ 2 = 4 {pop}

6 15 4 ^ - 3 +

15 ^ 4 = 50625 {pop}

6 50625 - 3 +

6 - 50625 = -50619 {pop}

-50619 3 +

-50619 + 3 = -50616

There's noffin left to pop so that's your answer.

Look a my sample snippet->http://www.daniweb.com/code/snippet599.html
Last edited by iamthwee : Mar 24th, 2007 at 4:41 am.
Member of: F-ugly code club

Join today don't delay!
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

DaniWeb Java Marketplace
Thread Tools Display Modes

Similar Threads
Other Threads in the Java Forum

All times are GMT -4. The time now is 9:50 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC