Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within Java in General
Search Coderanch
Advance search
Google search
Register / Login
Post Reply
Bookmark Topic
Watch Topic
New Topic
programming forums
Java
Mobile
Certification
Databases
Caching
Books
Engineering
Micro Controllers
OS
Languages
Paradigms
IDEs
Build Tools
Frameworks
Application Servers
Open Source
This Site
Careers
Other
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Campbell Ritchie
Jeanne Boyarsky
Ron McLeod
Paul Clapham
Liutauras Vilda
Sheriffs:
paul wheaton
Rob Spoor
Devaka Cooray
Saloon Keepers:
Stephan van Hulst
Tim Holloway
Carey Brown
Frits Walraven
Tim Moores
Bartenders:
Mikalai Zaikin
Forum:
Java in General
Evaluate Basic String Expression to do arithmatic calculation in the range of 0 to 9 numbers
Hitesh Patel Patel
Greenhorn
Posts: 28
posted 9 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
This program does basic
string
expression evaluation without using any of its relevant
java
in-build functions.
public class MathDemo2 { public static void main(String[] args) throws Exception{ String str = null; if(args != null && args.length > 0){ str = args[0]; } else { str = "5+2-1"; } float result = MathDemo2.processStrExpression(str); System.out.println("result = " + result); } public static float processStrExpression(String str){ float result = 0; float num1 = 0; for(int i=0; i<str.length(); i++){ char op = 'Z'; float num2 = 0; for(int j=i; j<str.length(); j++){ char ch = str.charAt(j); System.out.println("INNER LOOP : ch = " + ch); if(ch == '+' || ch == '-' || ch == '*' || ch == '/') { op = ch; } else { num2 = Float.parseFloat(Character.toString(ch)); } System.out.println("op = " + op + "; num2 = " + num2); if(num2 > 0 && op != 'Z'){ i = j; break; } else if(i==0 && num2 > 0){ i = j; op = '+'; //default first time break; } } if(op == '+'){ result = num1 + num2; } else if(op == '-'){ result = num1 - num2; } else if(op == '/'){ result = num1 / num2; } else if(op == '*'){ result = num1 * num2; } System.out.println("OUTER LOOP : num1 = " + num1 + "; op =" + op + "; num2 =" + num2 + "; result =" + result +"\n"); num1 = result; } return result; } }
Thanks,
Hitesh Patel
Sydney
Campbell Ritchie
Marshal
Posts: 79177
377
posted 9 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Do you have a question?
Did you see how Paul
cut 87% off of his electric heat bill with 82 watts of micro heaters
?
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
Calculator program
function call
Need help with Exception Handling
Switch Case Problem
Trouble evaluating postfix Expression
More...