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;
                 }
    }


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

How to implement a linked list inside another linked list…



This program let user to input a series of integer type inputs and they are stored in a Linked List based data structure. And there are several number of operations that user can use to access, maintain and manipulate the data in this data structure. Actually this data structure is a two dimensional Linked List. That means in this data structure we are using a Linked List in a Linked List concept. There are many horizontal Linked Lists which are stored in a one main vertical Linked List. Because of that the user can store any number of inputs in this data structure.



We can use an array as the main vertical Linked List. But it reduces the efficiency of the data structure. Using a Linked List in a Linked List concept we can store any number of data items because this data structure can be grow in both vertically and horizontally.
In this program first of all let user to input a series of integers and user can decide the place where they should be stored in this data structure. Then it provides seven main command that user can use to maintain those data. They are,
  • Print - Prints a full structure of given data structure. We can use this command to find how those inputs are stored in the data structure.   
  • Size - This command gives the number of data items in this data structure.
  • Insert - User can insert a given number to any sub list. Have to provide the index of the place that he wishes to insert the number. {Main Index, Sub Index}
  • Delete - User can delete a given number from any sub list. Have to provide the index of the place of the number that he wishes to remove from the list. {Main Index, Sub Index}
  • Search - Searching a particular number on the data structure and returns the Index of that number where it found in first.
  • Delete List - Delete a particular linked list on this data structure.
  • Insert List - Insert a particular linked list to this data structure.


The building box of this program is linked list. What is a linked list?  Linked List is a very common way of storing arrays of data. The major benefit of linked list is that you do not specify a fixed size for your list. The more elements you add to the chain, the bigger the chain gets.
When I designing this program first of all I have create a one Linked List. Then I stored that type of linked lists in a one main list. Following diagram will help you to understand the main attitudes of a linked list.


           In my basic linked list there are three classes. They are Node, List and Main. This is the implementation of my basic linked list.

Implementation of the Basic Linked List

Class Node
package linkedlists;

class Node {
int value;
                 Node next;

                public Node(){//constructor for a head
                                value=0;
                                next=null;
                 }

                public Node(int x){ //constructor for a normal node
                                value=x;
                                next=null;
                }
}

Class List
package linkedlists;

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,int 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(int 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);
                                }
                }
}

Class Main
package linkedlists;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
                List newList=new List();
                Scanner scan = new Scanner(System.in);
                Scanner cmd = new Scanner(System.in);
                int key=0;
               
                System.out.println("Please input your integer type input series. After input enter any letter.");
                while (scan.hasNextInt()) {
                                newList.insertHead(scan.nextInt());
                }      
                do{
                                System.out.println("1.Print");
                                System.out.println("2.Size");
                                System.out.println("3.Insert");
                                System.out.println("4.Delete");
                                System.out.println("5.Search");
                                System.out.println("6.Emptey list");
                                System.out.println("7.Exit");
                                System.out.println("Please enter your command.");
          
           try{   
                                key=cmd.nextInt();//nextInt() throws exception
           }catch(Exception Ex){
                                System.out.println("Please input an integer.");
                                key=0;
                                cmd = new Scanner(System.in);//creat new scanner object
           }

switch (key) {
                                case 1://print 
                                                newList.printNode();     
                                                break;
                                case 2://get size 
                                                System.out.println("Size is "+newList.size());     
                                                break;
                                case 3://insert 
                                                Scanner insertIndexInt = new Scanner(System.in);
                                                Scanner insertValInt = new Scanner(System.in);
                                 try{
System.out.println("Index for insert : ");
                                                                 int a=insertIndexInt.nextInt();
                                                                System.out.println("Value for insert : ");
                                                                int b=insertValInt.nextInt();
                   
                                                                newList.insert(a, b);   
                                                }catch(Exception ExInsertIndex){
                                                                System.out.println("Please input an integer.");
                                                }        
                                                break;
                                case 4://delete 
                                                System.out.println("Index for delete : ");
                                                Scanner deleteInt = new Scanner(System.in);
                                                try{
                                                                 int y=deleteInt.nextInt();
                                                                newList.delete(y);
                                                }catch(Exception ExDelete){
                                                                System.out.println("Please input an integer.");
                                 }
                                                break;


                                case 5://search  
                                                System.out.println("Integer for search : ");
                                 Scanner searchInt = new Scanner(System.in);
                                 try{
                                                                 int x=searchInt.nextInt();
                                                                 newList.search(x);
                                                }catch(Exception ExSearch){
                                                                System.out.println("Please input an integer.");
                                                }
                                                break;
                                 case 6://empty list 
                                                newList.makeEmpty();         
                                                break;
                                case 7://exit 
                                                System.out.println("END");         
                                                break;
                                default:
                                                System.out.println("Please input a integer between 1 - 7. ");
                                 break;
                }
        }while(key!=7)
 }
}

After the implementation of the basic linked list, I have tried to store a linked list in another linked list. To that I have to insert a List type variable to my class Node. Also I have added a special constructor to construct that type of Nodes. Each node in my vertical linked list contains a horizontal linked list.