Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Stack;
- public class Parsing{
- public static void main (String...args){
- String a = "((15/(7-(1+1)))*3)-(2+(1+1))";
- Stack<String> b = prepareExpression(a);
- for (String x : b) System.out.printf("%s ",x);
- System.out.println();
- double k = expression(b);
- System.out.println(k);
- }
- public static Stack<String> prepareExpression(String a){ // seperates operators/digits (Stack already reversed in order to evaluate left to right)
- Stack<String> result = new Stack<String>();
- String numberBuffer = "";
- for (int i = a.length()-1; i>=0;i--){
- char k = a.charAt(i);
- if (Character.isDigit(k)) numberBuffer=k+numberBuffer;// digits
- else if (k=='-' || k =='.' || k =='E'){ // possible digits
- if (k=='-') {
- if (i==0) numberBuffer=k+numberBuffer;
- else if (a.charAt(i-1) =='(' || a.charAt(i-1) =='E') numberBuffer=k+numberBuffer;
- //else if (a.charAt(i-1) ==' ') numberBuffer=k+numberBuffer; // OPTIONAL 2+ -1 ('2','+',' ','-','1') will be valid (will convert to -1)
- else {
- if (!numberBuffer.isEmpty()){
- result.push(numberBuffer);
- numberBuffer="";
- }
- result.push(Character.toString(k));
- }
- }
- else if (k=='.' || k=='E') numberBuffer=k+numberBuffer;
- }
- else if (k=='+'|| k =='*'|| k =='/'|| k =='^'|| k =='('|| k ==')') { // nondigits
- if (!numberBuffer.isEmpty()){
- result.push(numberBuffer);
- numberBuffer="";
- }
- result.push(Character.toString(k));
- }
- else System.out.println("Bad input");
- }
- if (!numberBuffer.isEmpty()) result.push(numberBuffer);
- return result;
- }
- public static double expression(Stack<String> a){
- double t=term(a);
- if (a.isEmpty()) return t;
- String operand = a.pop();
- if (operand.matches("\\+")){
- return t+term(a);
- }
- else if (operand.matches("-")){
- return t-term(a);
- }
- else {
- a.push(operand);
- }
- return t;
- }
- public static double term(Stack<String> a){
- double t = additionals(a);
- if (a.isEmpty()) return t;
- String operand = a.pop();
- if (operand.matches("\\*")){
- return t*additionals(a);
- }
- else if (operand.matches("/")){
- return t/additionals(a);
- }
- else {
- a.push(operand);
- }
- return t;
- }
- public static double additionals(Stack<String> a){
- double t = primary(a);
- if (a.isEmpty()) return t;
- String operand = a.pop();
- if (operand.matches("\\^")){
- return Math.pow(t,primary(a));
- } else{
- a.push(operand);
- }
- return t;
- }
- public static double primary(Stack<String> a){
- String k = a.pop();
- if (k.matches("\\(")){
- double d = expression(a);
- if (!a.pop().matches("\\)")){
- System.out.println("hi");
- }
- return d;
- }
- return Double.parseDouble(k);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement