Page 1 of 2 12 LastLast
Results 1 to 20 of 24
  1. #1
    FlemaVerde is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default Mathematical Expression Validation

    hi everyone! i'm new to this forum, and i'm having some "Logic trouble" in this problem...because i need to use stacks in validating the Mathematical Expression...and the problem goes in this condition:

    1.) user will input the expression.
    2.) use stacks
    3.) and display if the expression is Valid or Invalid


    any help would be appreciated! reach me thru this thread. Thanks in advance and more Power to this forum :)

  2. #2
    nap_patague is offline Member
    Join Date
    Mar 2011
    Location
    Bulacan, Philippines
    Posts
    23
    Rep Power
    0

    Default

    you can use regex to divide the math expression and then validate them
    Keep Moving Forward

  3. #3
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Just to help me out, show me a valid and invalid expression.

    Do you know how a stack works? Push all the individual items on and then pop and test each item.

  4. #4
    FlemaVerde is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    Tnx for the fast reply!

    actually i don't know how to implement that reg ex thingy...

    my java knowledge is still @ nomad lvl haha :p

  5. #5
    FlemaVerde is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    a+b = Valid
    c+b*a = Valid
    a+ = Invalid
    +a = Invalid

    Expressions with Grouping symbols

    (a+b)+c = Valid
    (a+b+c = Invalid
    a+c) = Invalid
    (a+b)c = Invalid

  6. #6
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Just push the whole thing onto the stack and pop it off and test each value, after each number the next item can only be a decimal, number or operator, after operators only a number or parenthesis.
    Last edited by sunde887; 03-20-2011 at 10:47 AM.

  7. #7
    FlemaVerde is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    actually those are just examples of the User's input...if i set the parameters with those, my program will be limited to those expressions.

  8. #8
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    And that's just an example of how to do it, your code may have to account for more things, but if you are supposed to use a stack then the above should work, however; others may have better advice. This is my advice and I believe it should be a good start on solving this.

  9. #9
    nap_patague is offline Member
    Join Date
    Mar 2011
    Location
    Bulacan, Philippines
    Posts
    23
    Rep Power
    0

    Default

    String pattern="[0-9a-z[0-9a-z]]";
    you can use that patten for checking the math expression on your sample expression
    Keep Moving Forward

  10. #10
    FlemaVerde is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    but how can implement that with Stacks?

    sorry for the noob questions...i'm not that great in Stacks and reg ex...

  11. #11
    nap_patague is offline Member
    Join Date
    Mar 2011
    Location
    Bulacan, Philippines
    Posts
    23
    Rep Power
    0

    Default

    there is already class stack included in java.

    java.util.Stack;
    Keep Moving Forward

  12. #12
    nap_patague is offline Member
    Join Date
    Mar 2011
    Location
    Bulacan, Philippines
    Posts
    23
    Rep Power
    0

    Default

    Java Code:
    import java.util.Stack;
    public class Sample2 {
            
       	private Stack s=new Stack();
        public static void main(String[] args) {
          
        }
        private void userInput(){
        	//do the userinput
        	s.push(userinput);
        }
        private void checkExpression(Stack s){
        	if(validExpression(s.pop().toString())){
        		System.out.println("Valid");
        	}else{
        		System.out.println("invalid");
        	}
        }
        private boolean validExpression(String s){
        	//do your logic here
        }
    }
    your code may be look like this.. you must work on the logic and validating the expression
    Keep Moving Forward

  13. #13
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,525
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by FlemaVerde View Post
    actually those are just examples of the User's input...if i set the parameters with those, my program will be limited to those expressions.
    To be more exact:

    1) if the current input is a number or a left parenthesis push it on the stack;
    2) if the current input is an operator, check the top two stack elements,
    if they are numbers perform the operation and push the result back on the stack;
    3) if the current input is a right parentesis, find a corresponding (topmost) left parenthesis on the stack and pop it.
    4) if the input is empty check the stack: it should contain a single numeric result.

    If any of the above operations fail the expression was syntactically invalid.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  14. #14
    FlemaVerde is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    tnx for the sample code...i'll try to work on the logic tnx a lot sir...hope to see your replies in my further questions! hehe

  15. #15
    FlemaVerde is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    Tnx Jos! i guess that answers all...but i really don't have any clue in making this kind of java program

  16. #16
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Great response jos, that's what I was trying to convey(not nearly as well though)

    @op: do you understand how to use a stack? Try making a small stack based program and work it to something more complex?

  17. #17
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,525
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by FlemaVerde View Post
    Tnx Jos! i guess that answers all...but i really don't have any clue in making this kind of java program
    Just for fun I'll post a small compiler that transforms an expression in infix notation to postfix notation; study it and you may use it for your own parser. Note that no tokenizer (lexical analyzer is included)

    Java Code:
    public class PostfixCompiler {
    
    	public static boolean isOperator(char token) {
    		
    		return "+-*/".indexOf(token) >= 0;
    	}
    	
    	public static class PostfixException extends Exception {
    		PostfixException(String error) { super(error); }
    	}
    	
    	private void pushLParen(StringBuffer stack) { stack.append('('); }
    		
    	private void popLParen(StringBuffer stack, StringBuffer output) 
    			throws PostfixException {
    		
    		int i= stack.lastIndexOf("(");
    		
    		if (i < 0) throw new PostfixException("unbalanced )");
    		
    		int n= stack.length();
    		for (int j= n-1;  j > i; j--)
    			output.append(stack.charAt(j));
    		
    		stack.delete(i, n);
    	}
    		
    	private int getPriority(char token) {
    		
    		switch (token) {
    			case '+':
    			case '-': return 1;
    			case '*':
    			case '/': return 2;
    			default : return 0;
    		}
    	}
    	
    	private void doOperand(StringBuffer postfix, char token) {
    		postfix.append(token);
    	}
    	
    	private void doOperator(StringBuffer stack, StringBuffer postfix, char token) {
    		
    		int prioIn= getPriority(token);
    		
    		for (int n= stack.length(); --n >= 0; stack.delete(n, n+1)) {
    			char stackToken= stack.charAt(n);
    			if (getPriority(stackToken) >= prioIn)
    				postfix.append(stackToken);
    			else
    				break;
    			}
    
    		stack.append(token);
    	}		
    		
    	private void flushStack(StringBuffer stack, StringBuffer postfix)
    			throws PostfixException {
    
    		for (int n= stack.length(); --n >= 0; stack.delete(n, n+1)) {
    			char stackToken= stack.charAt(n);
    			if (stackToken == '(')
    				throw new PostfixException("unbalanced (");
    			postfix.append(stackToken);
    		}
    	}
    
    	private boolean checkState(boolean operand, boolean state) 
    			throws PostfixException {
    		if (operand != state)
    			throw new PostfixException((operand?"operand":"operator")+" expected");
    			
    		return state;
    	}
    	
    	public String compile(String expr) throws PostfixException {
    	
    		StringBuffer stack= new StringBuffer();
    		StringBuffer postfix= new StringBuffer();
    
    		boolean operandState= true;
    				 
    		for (int i= 0, n= expr.length(); i < n; i++) {
    	
    			char token= expr.charAt(i);
    	
    			if (isOperator(token)) {
    				operandState= !checkState(operandState, false);
    				doOperator(stack, postfix, token);
    			}
    			else {
    				switch (token) {
    					case ')': operandState= checkState(operandState, false);
    							  popLParen(stack, postfix);
    							  break;
    						  
    					case '(': operandState= checkState(operandState, true);
    							  pushLParen(stack);
    							  break;
    						  
    					case ' ':
    					case '\t': break;
    				
    					default : operandState= !checkState(operandState, true); 
    							  doOperand(postfix, token);
    							  break;
    				}
    			}
    		}
    
    		flushStack(stack, postfix);
    					
    		return postfix.toString();
    	}
    }
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  18. #18
    FlemaVerde is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    --------------------Configuration: <Default>--------------------
    java.lang.NoSuchMethodError: main
    Exception in thread "main"
    Process completed.

    Tnx for the code jos! but it reflected those things...
    Tnx for the continuous help brother :)

  19. #19
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,525
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by FlemaVerde View Post
    --------------------Configuration: <Default>--------------------
    java.lang.NoSuchMethodError: main
    Exception in thread "main"
    Process completed.

    Tnx for the code jos! but it reflected those things...
    Tnx for the continuous help brother :)
    Of course, that class doesn't have a main method; you have to implement your own class with a main( ... ) method that constructs a PostfixCompiler, compiles your String; the return value of the compile( ... ) method is the postfix representation of the compiled expression. I can post a TreeCompiler that uses a PostfixCompiler and evaluates the tree (AST) it generated; if you want/need further spoonfeeding that is ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  20. #20
    FlemaVerde is offline Member
    Join Date
    Mar 2011
    Posts
    12
    Rep Power
    0

    Default

    hi to all! i have made a program regarding my problem...and i only come up with character validation...hmmm and i guess i still need to check for the precedents, location of each char, and pairs of each grouping symbol...and honestly i don't know how to start those stuffs...the cod of my character validation is as follows:

    Java Code:
    import java.util.*;
    
    public class jed2{
    	public static void main(String[]args){
    		Scanner x = new Scanner(System.in);
    		Stack stack = new Stack();
    		String input = "";
    		int i = 0;
    		int j = 0;
    		int k = 0;
    		char allows[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m'
    			,'n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2'
    			,'3','4','5','6','7','8','9','+','-','*','/','(',')'};
    
    			System.out.print("Enter Expression: ");
    			input = x.nextLine();
    			if(input.contains(" ")){
    				System.out.print("Invalid!");
    				System.exit(0);
    			}
    			char inputArray[] = input.toCharArray();
    			for(i=0;i<inputArray.length;i++){
    				stack.push(input.charAt(i));
    				System.out.print(i);
    			}while(!stack.empty()){
    				for(j=0;j<input.length();j++){
    					for(k=0;k<allows.length;k++){
    						if(inputArray[j]==allows[k]){
    							System.out.print("Valid!");
    							System.exit(1);
    						}if(inputArray[j]!=allows[k]){
    							System.out.print("Invalid!");
    							System.exit(2);
    						}
    					}
    				}
    			}
    	}
    }

Page 1 of 2 12 LastLast

Similar Threads

  1. Mathematical functions
    By Stev in forum New To Java
    Replies: 14
    Last Post: 11-27-2010, 02:08 PM
  2. Replies: 1
    Last Post: 11-22-2010, 09:10 PM
  3. Help: Mathematical Expressions
    By JohnAtick in forum New To Java
    Replies: 3
    Last Post: 03-09-2009, 06:02 PM
  4. Help with mathematical part in java
    By lenny in forum Advanced Java
    Replies: 3
    Last Post: 08-09-2007, 01:55 PM
  5. Help with mathematical methods
    By Marcus in forum Advanced Java
    Replies: 2
    Last Post: 07-01-2007, 08:20 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •