Results 1 to 20 of 24
 03202011, 09:24 AM #1Member
 Join Date
 Mar 2011
 Posts
 12
 Rep Power
 0
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 :)
 03202011, 09:28 AM #2Member
 Join Date
 Mar 2011
 Location
 Bulacan, Philippines
 Posts
 23
 Rep Power
 0
you can use regex to divide the math expression and then validate them
Keep Moving Forward
 03202011, 10:11 AM #3
 Join Date
 Jan 2011
 Location
 Richmond, Virginia
 Posts
 3,069
 Blog Entries
 3
 Rep Power
 8
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.
 03202011, 10:13 AM #4Member
 Join Date
 Mar 2011
 Posts
 12
 Rep Power
 0
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
 03202011, 10:17 AM #5Member
 Join Date
 Mar 2011
 Posts
 12
 Rep Power
 0
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
 03202011, 10:43 AM #6
 Join Date
 Jan 2011
 Location
 Richmond, Virginia
 Posts
 3,069
 Blog Entries
 3
 Rep Power
 8
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; 03202011 at 10:47 AM.
 03202011, 10:58 AM #7Member
 Join Date
 Mar 2011
 Posts
 12
 Rep Power
 0
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.
 03202011, 11:04 AM #8
 Join Date
 Jan 2011
 Location
 Richmond, Virginia
 Posts
 3,069
 Blog Entries
 3
 Rep Power
 8
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.
 03202011, 11:10 AM #9Member
 Join Date
 Mar 2011
 Location
 Bulacan, Philippines
 Posts
 23
 Rep Power
 0
String pattern="[09az[09az]]";Keep Moving Forward
 03202011, 11:12 AM #10Member
 Join Date
 Mar 2011
 Posts
 12
 Rep Power
 0
but how can implement that with Stacks?
sorry for the noob questions...i'm not that great in Stacks and reg ex...
 03202011, 11:19 AM #11Member
 Join Date
 Mar 2011
 Location
 Bulacan, Philippines
 Posts
 23
 Rep Power
 0
there is already class stack included in java.
java.util.Stack;Keep Moving Forward
 03202011, 11:26 AM #12Member
 Join Date
 Mar 2011
 Location
 Bulacan, Philippines
 Posts
 23
 Rep Power
 0
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 } }
Keep Moving Forward
 03202011, 11:33 AM #13
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 13,018
 Blog Entries
 7
 Rep Power
 20
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,
Joscenosillicaphobia: the fear for an empty beer glass
 03202011, 11:35 AM #14Member
 Join Date
 Mar 2011
 Posts
 12
 Rep Power
 0
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
 03202011, 12:58 PM #15Member
 Join Date
 Mar 2011
 Posts
 12
 Rep Power
 0
Tnx Jos! i guess that answers all...but i really don't have any clue in making this kind of java program
 03202011, 01:07 PM #16
 Join Date
 Jan 2011
 Location
 Richmond, Virginia
 Posts
 3,069
 Blog Entries
 3
 Rep Power
 8
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?
 03202011, 01:15 PM #17
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 13,018
 Blog Entries
 7
 Rep Power
 20
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= n1; 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(); } }
Joscenosillicaphobia: the fear for an empty beer glass
 03202011, 01:19 PM #18Member
 Join Date
 Mar 2011
 Posts
 12
 Rep Power
 0
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 :)
 03202011, 01:22 PM #19
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 13,018
 Blog Entries
 7
 Rep Power
 20
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,
Joscenosillicaphobia: the fear for an empty beer glass
 03212011, 12:10 AM #20Member
 Join Date
 Mar 2011
 Posts
 12
 Rep Power
 0
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); } } } } } }
Similar Threads

Mathematical functions
By Stev in forum New To JavaReplies: 14Last Post: 11272010, 02:08 PM 
How to evaluate the mathematical expression from the string in J2ME
By SIVAKUMAR.J in forum CLDC and MIDPReplies: 1Last Post: 11222010, 09:10 PM 
Help: Mathematical Expressions
By JohnAtick in forum New To JavaReplies: 3Last Post: 03092009, 06:02 PM 
Help with mathematical part in java
By lenny in forum Advanced JavaReplies: 3Last Post: 08092007, 01:55 PM 
Help with mathematical methods
By Marcus in forum Advanced JavaReplies: 2Last Post: 07012007, 08:20 PM
Bookmarks