Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Threaded View

  1. #1
    Junior Member
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Help with modifying a program for evaluating arithmetic expressions

    This is an assignment for a data structures class that I need a little help getting started with. We are given all of the code that I provided below and we are asked to modify it so that the program for evaluating arithmetic expressions will also allow the unary operation '-'. For example, for the expression "-1" the result is -1; for the expression "-(1+3)" the result is -4; etc.

    I am not asking for the answer, I just need some direction in how to get started. Any help is much appreciated. Thank you.

    package cs272;
     
    import java.util.Scanner;
    import java.util.regex.Pattern;
     
    import edu.colorado.collections.LinkedStack;
     
    public class Evaluation {
     
    	/**
    	 * @param args
    	 */
     
    	private static boolean TRACE = false; 
     
    	public static final Pattern CHARACTER =
    		     Pattern.compile("\\S.*?");  
    	public static final Pattern UNSIGNED_DOUBLE =
    		     Pattern.compile("((\\d+\\.?\\d*)|(\\.\\d+))([Ee][-+]?\\d+)?.*?");	
     
    	public static void printStack(LinkedStack<String> st) {
    		LinkedStack<String> pr = st; 
     
    		while (!pr.isEmpty()) {
    			System.out.print(pr.pop() +" ");
    		}
     
    	}
     
    	public static LinkedStack<String> reverseStack(LinkedStack<String> st) {
    		LinkedStack<String> rev = new LinkedStack<String>();
     
    		while (!st.isEmpty()) {
    			 rev.push(st.pop());
     		}
    		return rev;
    	}
     
    	public static double calculate(LinkedStack<Double> operands, Character operation)
    	{
    		double op1 = operands.pop();
    		double op2 = operands.pop();
    		double result = 0; 
     
    		if (TRACE) System.out.println("op1 "+op1 +" op2 "+op2 +" " + operation);
     
    		switch(operation) 
    		{
         	case '+': 
         		result = op2 + op1; 
         		break; 
         	case '-': 
         		result = op2 - op1; 
         		break; 
         	case '*': 
         		result = op2 * op1; 
         		break; 
         	case '/': 
         		result = op2 / op1; 
         		break; 
    		}
    		return result;
    	}
     
    	public static double evaluation(LinkedStack<String> st)
    	{
    		LinkedStack<Double> operands = new LinkedStack<Double>();
    		String next;
     
    		while (!st.isEmpty())
    		{
    		     next = st.pop();
    		     if (TRACE)  System.out.println("Processing "+next);
    		     switch (next.charAt(0)) 
    		     {
    		     	case '+': 
    		     	case '-': 
    		     	case '*': 
    		     	case '/': 
    		     		operands.push(calculate(operands, next.charAt(0)));
    		     		break; 
    		    	default:  
    		    		operands.push(Double.valueOf(next)); 
    		    		break; 
    		     }
    		}		
    		return operands.pop(); 
    	}
     
    	public static LinkedStack<String> infix2postfix(String s) {
    		LinkedStack<String> results = new LinkedStack<String>();
    		LinkedStack<Character> operations = new LinkedStack<Character>();
    		Scanner input = new Scanner(s);
    		String next;
    		Character first; 
     
    		while (input.hasNext())
    		{
    			 if (input.hasNext(UNSIGNED_DOUBLE))
    			 {
    			    next = input.findInLine(UNSIGNED_DOUBLE);
    			    results.push(next);
    			    if (TRACE)  System.out.println("Processing "+next); 
     			 }
    			 else
    			 {
    			    next = input.findInLine(CHARACTER);
    			    if (TRACE)  System.out.println("Processing "+next+" size of operations stack "+operations.size()); 
     
    			    first = next.charAt(0);
     
    			    switch (first)
    			    {
    			    case '+': // Addition
    			    case '-': // Substraction
    				    // System.out.println(" ... size of operations stack before do-while "+operations.size()); 
     
    				    while (!operations.isEmpty() && !operations.peek().equals('('))
    			    	{
    				    	   Character op = operations.pop();
    				    	   String sop = Character.toString(op);
    				    	   results.push((String) sop);
    			    	}
     
    				    // System.out.println(" ... size of operations stack after do-while "+operations.size()); 
     
    			    	operations.push(first);
    			       break; 
    			    case '*': // Multiplication
    			    case '/': // Division
    				    while (!operations.isEmpty() && 
    					    	   !(operations.peek().equals('(') || 
    					    	     operations.peek().equals('+') || 
    					    	     operations.peek().equals('-') 	   
    					    	    )
    					    	  )
    			    	{
    				    	   Character op = operations.pop();
    				    	   String sop = Character.toString(op);
    				    	   results.push(sop);
    			    	}
    			    	operations.push(first);
    			    	break;
    			    case ')': // Right parenthesis
    			       while (!operations.isEmpty() && !operations.peek().equals('('))
    			       {
    			    	   Character op = operations.pop();
    			    	   String sop = Character.toString(op);
    			    	   results.push(sop);
    			       }
    			       if (operations.isEmpty())
    			    	   throw new IllegalArgumentException("Invalid Expression"); 
    			       operations.pop();
    			       break;
    			    case '(': // Left parenthesis
    				       operations.push(first);
    			    	break;
    			    default : // Illegal character
    			       throw new IllegalArgumentException("Illegal character");
    			    }			    
    			 }
    			 // System.out.println(next);			
     
    		}
     
    	    while (!operations.isEmpty())
    	       {
    	    	   Character op = operations.pop();
    	    	   String sop = Character.toString(op);
    	    	   results.push(sop);
    	       }
     
    		return results; 
     
    	}
     
    	// evaluate a fully parenthesized arithmetic expression 
     
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
     
    		String  exp = args[0]; 
    		LinkedStack<String> rev; 
     
    		System.out.println("Expression: "+exp);
    		LinkedStack<String> postfix = infix2postfix(exp);		
    		rev = reverseStack(postfix);
    		printStack(rev.clone()); 
    		System.out.println("\nEvaluation: "+evaluation(rev));
     
    	}
     
    }
    Last edited by KevinWorkman; October 12th, 2011 at 07:16 AM. Reason: please use highlight tags when posting code!


Similar Threads

  1. Stack Practice: Evaluating Expressions Syntax
    By Staticity in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 4th, 2011, 10:35 PM
  2. Modifying "Coin change" program
    By S0ULphIRE in forum Algorithms & Recursion
    Replies: 33
    Last Post: September 18th, 2011, 11:38 PM
  3. [SOLVED] evaluating postfix expressions using stack
    By lieles in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 16th, 2011, 11:48 AM
  4. Evaluating Expressions
    By javapenguin in forum What's Wrong With My Code?
    Replies: 19
    Last Post: November 16th, 2010, 08:30 PM
  5. Arithmetic’s Game ??
    By holy crab in forum Algorithms & Recursion
    Replies: 0
    Last Post: April 12th, 2010, 04:27 AM