Created
November 20, 2015 11:17
-
-
Save serhii-shnurenko/f5cbfded06becce4e1fb to your computer and use it in GitHub Desktop.
Simple arithmetic expression parser, can do 4 basic arithmetic actions +-*/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
/** | |
* Created by Сергій Шнуренко on 18.11.2015. | |
*/ | |
public class ExpressionNode { | |
private ExpressionNode arg1; | |
private ExpressionNode arg2; | |
private String value; | |
public ExpressionNode(String value){ | |
int currentPriority=3; | |
int lowestPriorityIndex=0; | |
char[] charArray = value.toCharArray(); | |
for(int i=0;i<charArray.length;i++){ | |
switch (charArray[i]){ | |
case '+': | |
currentPriority = 1; | |
lowestPriorityIndex = i; | |
break; | |
case '-': | |
currentPriority = 1; | |
lowestPriorityIndex = i; | |
break; | |
case '*': | |
if(currentPriority>2) { | |
currentPriority = 2; | |
lowestPriorityIndex = i; | |
} | |
break; | |
case '/': | |
if(currentPriority>2) { | |
currentPriority = 2; | |
lowestPriorityIndex = i; | |
} | |
break; | |
} | |
} | |
if(lowestPriorityIndex==0){ | |
this.value = value; | |
arg1 = null; | |
arg2 = null; | |
}else{ | |
this.value =String.valueOf(charArray[lowestPriorityIndex]); | |
this.arg1 = new ExpressionNode(value.substring(0,lowestPriorityIndex)); | |
this.arg2 = new ExpressionNode(value.substring(lowestPriorityIndex+1,value.length())); | |
} | |
} | |
public double getNumValue(){ | |
if (value.equals("+")){ | |
return arg1.getNumValue()+arg2.getNumValue(); | |
}else if(value.equals("-")){ | |
return arg1.getNumValue()-arg2.getNumValue(); | |
}else if(value.equals("*")){ | |
return arg1.getNumValue()*arg2.getNumValue(); | |
}else if(value.equals("/")){ | |
return arg1.getNumValue()/arg2.getNumValue(); | |
}else { | |
return Double.parseDouble(value); | |
} | |
} | |
public String toString(){ | |
if(arg1==null&&arg2==null) | |
return value; | |
else | |
return arg1.toString()+value+arg2.toString(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
public class Main { | |
public static void main(String[] args) { | |
ExpressionNode head = new ExpressionNode("99*99-1"); | |
System.out.println(head.getNumValue()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment