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

Thread: Help with modifying a program for evaluating arithmetic expressions

  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!


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Help with modifying a program for evaluating arithmetic expressions

    That's a lot of code. We have a ton of posts to answer here every day, so we don't have time to wade through that many lines of code without a more specific answer. I recommend you read through this: http://www.javaprogrammingforums.com...e-posting.html
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

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

    Default Re: Help with modifying a program for evaluating arithmetic expressions

    Well that's really not that much code, but that's fine if you can't help. I'll just leave it up in case somebody else can help and if not I'll try somewhere else. Thanks anyway.

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Help with modifying a program for evaluating arithmetic expressions

    Quote Originally Posted by rockout341 View Post
    Well that's really not that much code, but that's fine if you can't help. I'll just leave it up in case somebody else can help and if not I'll try somewhere else. Thanks anyway.
    Sure, it's not that much code for any particular project, but it is quite a bit of code for strangers to look at for free, in their spare time, at the cost of helping others in the time it takes to wade through it. We're here to help, but we could help 5 other people in the time it takes to look through your code. Is your time really that much more valuable than theirs, or ours? 200 lines is about 10 times longer than a good example should be, and you're going to hear this no matter where you go.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

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

    Default Re: Help with modifying a program for evaluating arithmetic expressions

    Thanks for taking the time to give me that warning. I'll keep that in mind when I need help with anything with more then a few lines of code to use different resources then this forum, but I found help else where so thanks anyway.

  6. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Help with modifying a program for evaluating arithmetic expressions

    This forum is a fine resource for people willing to show some effort. You're going to get the same response at every technical forum, probably in a much ruder way, for exactly the reasons I outlined above. Good luck though.

    More recommended reading: http://www.javaprogrammingforums.com...-get-help.html
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

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