Monday, January 9, 2012

Creating a simple calculator



This calculator program let user to input an arbitrary equation through a graphical interface and display the answer according to BODMAS law. This equation can have all components including parentheses, addition subtraction, multiplication and division.  These system specifications were given.

Description

Your task is to create a program which simulates very simple calculator. The details for the implementation of the system are given in the steps below:

  • .        Design and implement an abstract base class ArithmeticExpression that represent any binary (having two arguments) arithmetic expression. In this coursework you will be implementing various subclasses of this class. The abstract class should include at least two methods called evaluate and display which are described below.
  • .  Design and implement concrete (non-abstract) classes which are subclasses of the class ArithmeticExpression and each one represent some simple arithmetic expression. The operations that you should implement for each subclass should include the binary (i.e. accepting exactly two arguments) operations of addition, subtraction, multiplication and division (all of them accepting double type arguments). Using the classes you should be able to represent an arbitrary expression (i.e. an expression with an arbitrary number of terms), for example an expression like (5.0+8.1)*(2.0) or ((5.0+8.1)*(2.0))/12.5” (not specifically in this format but represent the overall expression in an equivalent way). To design your classes you should think what common functionality and differences (fields and methods) these classes share and place such functionality at the appropriate place of the class hierarchy. Implement methods evaluate and display. Method evaluate evaluates the arithmetic expression that the object represents and returns the result as a double. For example, calling it in an object representing expression (5.0+8.1)*(2.0)   should return 26.2. Method display prints the raw (unevaluated) expression on the screen. For example, calling it in an object representing expression (5.0+8.1)*(2.0) should display the string (5.0+8.1)*(2.0) (without the quotes).You should NOT use static methods!
  • .      Implement a test class CalculatorTest which tests the functionality of your classes (the methods of your classes should be called and make sure that they do what they are supposed to do).
  • .     Implement a class RandomCalculations which automatically creates a random number of random expressions and uses your classes above to evaluate and display them. Every time that this class is run, a deferent number of deferent random expressions is evaluated and displayed. Test its functionality by calling its methods in the CalculatorTest class above.

First of all I have created an abstract class ArithmeticExpression and it has 2 abstract methods evaluate and display. And also it has two variables x, y.
Using that abstract class I have created four concrete classes for each arithmetic operation. Use these classes to do binary expressions.
When we are evaluating particular arbitrary expression we have to follow the BODMAS law. So there are three main ways to do this evaluation.
First one is using String class methods. Take the expression as a String and using String class methods and we can turn that into BODMAS pattern. But it takes huge amount of lines of code. So it is not a good way to implement an advanced calculator.
Second method is using a binary tree. It is very good and interesting way to break down the equation according to BODMAS. Following diagram shows how to do this using the split () method in String class.


Take the equation 2+5/6-(4+7*9). First of all we have to break it from parentheses. Then according to BODMAS we can store the expression in that tree.
Then we have to do the evaluation. We can use post order traversal method to travel through nodes and take the final answer.  But when it is a large expression the height of the binary tree rapidly increases. That means the efficiency of tree goes down. So this is also not a good way to evaluate a big expression.
Third and most suitable way to do this BODMAS evaluation is using STACKs. Using stacks we can turn this expression into Rivers Polish Notation (RPN). Last semester of the 1st year we had learnt about that in Software Development Principals. We can use one Stack and 2 string variables and successfully evaluate any large expression. This is the algorithm.
Stacks are used by compilers to helping the process of evaluating expressions and generating machine-language code. In this and the next exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. Humans generally write expressions like3+4and7/9in which the operator (+ or / here) is written between its operands—this is called infix notation. Computers “prefer” postfix notation, in which the operator is written to the right of its two operands. The preceding infix expressions would appear in postfix notation as 34+and79/, respectively.
To evaluate a complex infix expression, a compiler would first convert the expression to postfix notation and evaluate the postfix version. Each of these algorithms requires only a single left-to right pass of the expression. Each algorithm uses a stack object in support of its operation, but each uses the stack for a different purpose. In this exercise, you will write a Java version of the infix-to-postfix conversion algorithm. In the next exercise, you will write a Java version of the postfix expression evaluation algorithm. In a later exercise, you will discover that code you write in this exercise can help you implement a complete working compiler.
Write class InfixToPostfixConverter to convert an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers such as (6 + 2)*5-8 / 4 to a postfix expression. The postfix version of the preceding infix expression is (note that no parentheses are needed)
6 2 +5*84 /
 The program should read the expression intoStringBufferinfix and use one of the stack classes implemented in this chapter to help create the postfix expression inStringBufferpostfix. The algorithm for creating a postfix expression is as follows:
a) Push a left parenthesis '(' on the stack.
b) Append a right parenthesis ')' to the end of infix.
c) While the stack is not empty, read infix from left to right and do the following:
ü  If the current character in infix is a digit, append it to postfix.
ü  If the current character in infix is a left parenthesis, push it onto the stack.
ü  If the current character in infix is an operator:
·         Pop operators (if there are any) at the top of the stack while they have equator higher precedence than the current operator, and append the popped operators to postfix.
·         Push the current character in infix onto the stack.
ü  If the current character in infix is a right parenthesis:
·         Pop operators from the top of the stack and append them to postfix until a left parenthesis is at the top of the stack.
·         Pop (and discard) the left parenthesis from the stack.
The stack should be maintained with stack nodes that each contain an instance variable and a reference to the next stack node. Some of the methods you may want to provide are as follows:
a) Method convertToPostfix, which converts the infix expression to postfix notation.
b) Method isOperator, which determines whether c is an operator.
c) Method precedence, which determines whether the precedence ofoperator1 (from the infix expression) is less than, equal to or greater than the precedence ofoperator2 (from the stack). The method returns trueifoperator1has lower precedence thanoperator2.
Otherwise, false is returned.
d) Method stackTop (this should be added to the stack class), which returns the top value of the stack without popping the stack. 
The program should read a postfix expression consisting of digits and operators into a StringBuffer.
Using modified versions of the stack methods implemented earlier in this chapter, the program should scan the expression and evaluate it (assume it is valid). The algorithm is as follows:
a) Append a right parenthesis ')' to the end of the postfix expression. When the right parenthesis character is encountered, no further processing is necessary.
b) When the right-parenthesis character has not been encountered, read the expression from left to right.
If the current character is a digit, do the following:
·         Push its integer value on the stack (the integer value of a digit character is its value in the computer’s character set minus the value of'0' in Unicode).
·         Otherwise, if the current character is an operator:
·         Pop the two top elements of the stack into variables x and y.
·         Calculate y operator x.
·         Push the result of the calculation onto the stack.
c) When the right parenthesis is encountered in the expression, pop the top value of the stack. This is the result of the postfix expression.
 First of all I have to create a stack using a linked list then I turned it into a stack and use it for evaluation.


package calculator;

class Node {
                                char value;
                                double data;
                                 Node next;

                public Node(){
                                value=' ';
                                next=null;
                 }
                public Node(char x){
                                value=x;
                                next=null;
                }
                 public Node(double y){
                                data=y;
                                next=null;
                }
}
 .....................................................................................................................................................
package calculator;

class List {
                Node head;

                public List(){
                                head=null;
                 }
                public boolean isEmpty(){
                                return head==null;
                }
                                public void delete(int index){
                                Node curr=head;
                                Node prev=null;
                                if(index>size()||index<1||isEmpty()==true){
                                                if(isEmpty()==true){
                                                                System.out.println("Empty list…");
                                                 }
                                                else{
                                                                System.out.println("Index should between 1 and list size.");
                                                }
                                }
                                else if(index==1){
                                                deleteHead();//delete index 1 = delete head
                                 }
                                else{
                                                for(int x=1;x<index;x++){
                                                                prev=curr;
                                                                curr=curr.next;
                                                 }
                                                prev.next=curr.next;
                                }
                }
                public void insert(int index,char value){
                                Node newPtr=new Node(value);
                                Node curr=head;
                                Node prev=null;
                                 if(index>size()+1||index<1){//can insert to index size()+1 means insert value to end
                                                System.out.println("Index should between 1 and list size.");
                                }
                                else if(index==1){
                                                insertHead(value);//insert index 1 = insert head
                                }
                                 else{
                                                 for(int x=1;x<index;x++){
                                                                prev=curr;
                                                                curr=curr.next;
                                                }
                                                newPtr.next=curr;
                                                 prev.next=newPtr;
                                 }
                }
                public void makeEmpty() {
                                 head= null;
                                System.out.println("Empty List....");
                }
                public int size(){
                                 int listSize=0;
                                Node a=head;
                                while(a!=null){
                                                 a=a.next;
                                                 listSize++;
                                }
                                 return listSize;
                }
                 public void insertHead(char x){
                                Node NewLink=new Node(x);
                                 if(head==null){
                                                 head=NewLink;
                                }
                                else{
                                                NewLink.next=head;
                                                head=NewLink;
                                }
                }
                 public void insertHead(double x){
                                Node NewLink=new Node(x);
                                 if(head==null){
                                                 head=NewLink;
                                }
                                else{
                                                NewLink.next=head;
                                                head=NewLink;
                                }
                }
                public void deleteHead(){
                if(head==null){
                                                System.out.println("Empty List....");
                                }
                                else {
                                                head=head.next;
                                }
                }
                public void search(int y){
                                Node curr=head;
                                 int index=0;
                                boolean isFound = false;
                                while(curr!=null){
                                                 index+=1;
                                                if(curr.value==y){
                                                                isFound=true;
                                                                System.out.println(y+" Found in index "+index);
                                                                curr=null;
                                                }
                                                 else{
                                                 curr=curr.next;
                                                 }
                                }
                                 if(isFound==false){
                                                System.out.println("Not Found...");
                                }
                }
   
                public void printNode(){
                                if(head==null){
                                                System.out.print("Empty List....");
                                }
                                for(Node a=head; a!=null; a=a.next){
                                                System.out.print(" "+a.value);
                                }
                }
}

.....................................................................................................................................................
package calculator;

public class ListStack extends List{
                 public void push(char c){
                                 insertHead(c);
                }
                 public void push(double c){
                                insertHead(c);
                }
                public void pop(){
                                 deleteHead();
                 }
                public char peek(){
                                 if(head==null){
                                                System.out.print("Empty List....");
                                }
                return head.value;
                 }
                public double dpeek(){
                                 if(head==null){
                                                System.out.print("Empty List....");
                                 }
                return head.data;
                }
    }
.....................................................................................................................................................package calculator;

public class InfixPostfixConverter {
                 StringBuffer infix;
                public InfixPostfixConverter(StringBuffer infix){
                                this.infix=infix;
                }
                public StringBuffer Convert(){
                                ListStack myStack=new ListStack();
                                StringBuffer postfix=new StringBuffer();
                                myStack.push('(');
                                infix=new StringBuffer(infix+")");

                                for(int i=0;i<infix.length();i++){
                                                 if(infix.charAt(i)>47 && infix.charAt(i)<58 || infix.charAt(i)=='.'){
                                postfix=new StringBuffer(postfix+Character.toString(infix.charAt(i)));
                                                  }
                                                 if(infix.charAt(i)=='('){
                                                myStack.push('(');
                                                }
                                                 if((infix.charAt(i) =='-') || (infix.charAt(i) =='+') || (infix.charAt(i) =='*') || (infix.charAt(i) =='/')){

                                                                 postfix=new StringBuffer(postfix+":");
                                                                 if(infix.charAt(i) ==47){
while(myStack.peek()!='*'&&myStack.peek()!='+'&&myStack.peek()!='-'&&myStack.peek()!='('){
               postfix=new StringBuffer(postfix+Character.toString((Character)myStack.peek())+":");
                myStack.pop();
  }
 myStack.push(infix.charAt(i));
               }
               if(infix.charAt(i) ==42){
               while(myStack.peek()!='+'&&myStack.peek()!='-'&&myStack.peek()!='('){
                 postfix=new StringBuffer(postfix+Character.toString((Character)myStack.peek())+":");
               myStack.pop();
               }
               myStack.push(infix.charAt(i));
               }
               if(infix.charAt(i) =='+'){
               while(myStack.peek()!='-'&&myStack.peek()!='('){
                   postfix=new StringBuffer(postfix+Character.toString((Character)myStack.peek())+":");
                   myStack.pop();
               }
               myStack.push(infix.charAt(i));
               }
               if(infix.charAt(i) =='-'){
               while(myStack.peek()!='('){
                   postfix=new StringBuffer(postfix+Character.toString((Character)myStack.peek())+":");
                   myStack.pop();
                  
               }
               myStack.push(infix.charAt(i));
               }
  }
           if(infix.charAt(i)==')'){
               while(myStack.peek()!='('){
                   postfix=new StringBuffer(postfix+":"+Character.toString(myStack.peek()));
                   myStack.pop();
               }
               myStack.pop();
           }
    }
return postfix;
}
}
.....................................................................................................................................................
package calculator;

public class ListStack extends List{
                public void push(char c){
                                 insertHead(c);
                }
                 public void push(double c){
                                insertHead(c);
                }
                public void pop(){
                                deleteHead();
                }
                public char peek(){
                                 if(head==null){
                                                System.out.print("Empty List....");
                                 }
                                 return head.value;
                 }
                public double dpeek(){
                                 if(head==null){
                                                 System.out.print("Empty List....");
                                 }
                return head.data;
                 }
    }


.....................................................................................................................................................

No comments:

Post a Comment