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 8 of 8

Thread: Java:Evaluation of Mathematical Expression only from left to right only.

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

    Default Java:Evaluation of Mathematical Expression only from left to right only.

    I have written a Java program which evaluates a mathematical expression from left to right only.however im stuck up with the output.Im not getting the desired output.
    Please Note: There is no precedence in operators(evaluation should be from LEFT->RIGHT.)

    /*
     * Created on Jul 10, 2011
     *
     * To change the template for this generated file go to
     * Window>Preferences>Java>Code Generation>Code and Comments
     */
    package com.comcast;
    import java.util.*;
    public class Evaluation
    {
        private static final char[] validOperators = {'/','*','+','-'};
     
    	private Evaluation()
    	{
    		 /* Using a private contructor to prevent instantiation
    			 Using class as a simple static utility class
    		 */
    	}
     
    	private static int evaluate(String leftSide, char oper, String rightSide)
    	 throws IllegalArgumentException
    	{
    		System.out.println("Evaluating: " + leftSide +  " (" + oper + ") " + rightSide);
    		int total = 0;
    		int leftResult = 0;
    		int rightResult = 0;
    		String originalString =leftSide;
    		int operatorLoc  = findOperatorLocation(leftSide);
    		leftSide = leftSide.substring(0,operatorLoc);
    		rightSide = originalString.substring(operatorLoc+1,operatorLoc+2);
    		String remainingString = originalString.substring(operatorLoc+2,originalString.length());
     
     
    		System.out.println("leftSide -->"+leftSide);
    		System.out.println("rightSide -->"+rightSide);
    		System.out.println("remainingString --->"+remainingString);
     
    	 try{
    			 leftResult = Integer.parseInt(leftSide);
    		}catch(Exception e){
    				throw new IllegalArgumentException("Invalid value found in portion of equation: "
    				  + leftSide);
    	    }
     
     
    	 try{
    			 rightResult = Integer.parseInt(rightSide);
    	   }catch(Exception e){
    				throw new IllegalArgumentException("Invalid value found in portion of equation: "
    				  + rightSide);
    	   }
     
     
    		System.out.println("Getting result of: " + leftResult + " " + oper + " " + rightResult);
    		switch(oper)
    		{
    			case '/':
    			 total = leftResult / rightResult; break;
    			case '*':
    			 total = leftResult * rightResult; break;
    			case '+':
    			 total = leftResult + rightResult; break;
    			case '-':
    			 total = leftResult - rightResult; break;
    			default:
    			 throw new IllegalArgumentException("Unknown operator.");
    		}
    		System.out.println("Returning a result of: " + total);
    		String totally = String.valueOf(total)+remainingString;
    		return evaluate(totally,findCharacter(totally),remainingString);
    	}
     
    	private static int findOperatorLocation(String string)
    		{
    			int index = -1;			
    				index = string.indexOf(string.substring(1,2));			    
    				if(index >= 0){				
    				 return index;
    				}
    			return index;
    		}
     
    	private static char findCharacter(String string){
     
    		char c='\u0000';  
    		int index = -1;			
    						index = string.indexOf(string.substring(1,2));
    						if(index >= 0){				
    						 c = string.charAt(index);
    						 return c;
    						} 		 			 	
    		 return c;	
    	}
     
    	public static int processEquation(String equation)
    	  throws IllegalArgumentException
    	{
    		  return evaluate(equation,'+',"0");
    	}
     
    	public static void main(String[] args)
    	{
    		//String usage = "Usage: java MathParser equation\nWhere equation is a series"
    		// + " of integers separated by valid operators (+,-,/,*)";
     
    		//if(args.length < 1 || args[0].length() == 0)
    		// System.out.println(usage);
    		Scanner input = new Scanner(System.in); 
    		System.out.print("Enter the equation to be evaluated ");
     
    		String equation = (String)input.next();
    			int result = Evaluation.processEquation(equation);
    		 System.out.println("The result of your equation ("
    			   + equation + ") is: " + result);
     
    		//catch(IllegalArgumentException iae)
    		//{
    		//	System.out.println(iae.getMessage() + "\n" + usage);
    		//}
    	}
    }


    Expression Input:3+5*2-5 =>3+5*2-5 =>8*2-5 =>16-5 =>Expected Output :11

    im getting as below output Enter the equation to be evaluated 3+5*2-5
    Evaluating: 3+5*2-5 (+) 0
    leftSide -->3
    rightSide -->5
    remainingString --->*2-5
    Getting result of: 3 + 5
    Returning a result of: 8
    Evaluating: 8*2-5 ( * ) *2-5
    leftSide -->8
    rightSide -->2
    remainingString --->-5
    Getting result of: 8 * 2
    Returning a result of: 16
    Evaluating: 16-5 (6) -5
    leftSide -->1
    rightSide -->-
    remainingString --->5
    Exception in thread "main" java.lang.IllegalArgumentException: Invalid value found in portion of equation: -
    at Evaluation.evaluate(Evaluation.java:49)
    at Evaluation.evaluate(Evaluation.java:70)
    at Evaluation.evaluate(Evaluation.java:70)
    at Evaluation.processEquation(Evaluation.java:98)
    at Evaluation.main(Evaluation.java:112)

    Im unable to make my program generic for any equation entered.Help provided will be appreciated.Please note this is not a homework question.
    Need help !!!!!Code fix required for the above program


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Java:Evaluation of Mathematical Expression only from left to right only.

    You must have a logic error or a bad expression.
    Have you tried more debugging aids by adding more printlns to show how the variables change?

  3. #3
    Junior Member
    Join Date
    Jul 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Unhappy Re: Java:Evaluation of Mathematical Expression only from left to right only.

    The problem is in the method operatorLoc where im hardcoding the subString(1,2) to find location of operator,when i encounter 16-5,it returns a wrong location for operator.which is (6) instead of (-).

    Need help in resolving this ? Please provide the bug fix for the same.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Java:Evaluation of Mathematical Expression only from left to right only.

    operatorLoc where im hardcoding the subString(1,2) to find location of operator,when i encounter 16-5,it returns a wrong location for operator.which is (6) instead of (-).
    Can you explain what this code is supposed to do:
    index = string.indexOf(string.substring(1,2));
    Also what different values will it return?

  5. #5
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Java:Evaluation of Mathematical Expression only from left to right only.

    Quote Originally Posted by deepakl_2000 View Post
    The problem is in the method operatorLoc where im hardcoding the subString(1,2)
    So don't do that. You can either split your String up so that 2 or more digit numbers stay as a whole number or parse your equation by reading until you reach an operator. Everything upto that point must be the operand.
    Improving the world one idiot at a time!

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

    Default Re: Java:Evaluation of Mathematical Expression only from left to right only.

    Hi Junky,Can you provide the code fix for my code.??

  7. #7
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Java:Evaluation of Mathematical Expression only from left to right only.

    No. It is your job to write it not mine.
    Improving the world one idiot at a time!

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Java:Evaluation of Mathematical Expression only from left to right only.

    Look at post#4 again. Can you describe what that code is supposed to do?
    The way it is coded, it will always set index to 1. Unless the string is too short.

Similar Threads

  1. Basic Math Expression Java Problem
    By andyluvskrissy in forum What's Wrong With My Code?
    Replies: 6
    Last Post: November 15th, 2011, 03:22 AM
  2. Regular Expression help
    By medoos in forum Java SE APIs
    Replies: 0
    Last Post: March 19th, 2011, 07:23 PM
  3. Left and Right rotation in a balanced binary tree problem
    By szuwi in forum Algorithms & Recursion
    Replies: 2
    Last Post: December 22nd, 2010, 07:20 PM
  4. Basic Math Expression Java Problem
    By andyluvskrissy in forum Object Oriented Programming
    Replies: 3
    Last Post: September 30th, 2010, 02:46 PM
  5. Using Regular Expression (regex) in Java Programming
    By lordelf007 in forum What's Wrong With My Code?
    Replies: 8
    Last Post: May 14th, 2010, 10:29 AM

Tags for this Thread