public class SimpleFunktionParser {
public static boolean isOperator(char c){
switch(c) {
case '+': return true;
case '-': return true;
case '*': return true;
case '/': return true;
default: return false;
}
}
public static ArrayList<Object> parse(String str){
boolean firstOrSecond= true;
char op = 0;
int result = 0;
boolean hasfoundOperator = false;
boolean firstDouble =false;
boolean secondDouble =false;
double firstInNumber = 0, secondInNumber= 0;
ArrayList<Object> set = new ArrayList<Object>(3);
str = str.replaceAll(" +", " ");
str = str.trim();
String firstInString = "", secondInString = "";
for(int i = 0;i <= str.length()-1;i++){
if (Character.isDigit(str.charAt(i))){
if (firstOrSecond){
firstInString += str.charAt(i);
}
else{
secondInString += str.charAt(i);
}
}
else if(str.charAt(i)== '.'){
if (firstOrSecond){
firstDouble = true;
firstInString += ".";
}
else{
secondDouble = true;
secondInString += ".";
}
}
else{
if(isOperator(str.charAt(i))){
firstOrSecond = false;
if(!hasfoundOperator){
op = str.charAt(i);
hasfoundOperator = true;
}
else{
throw new IllegalArgumentException( "Only one Operator is allowed!!" );
}
}
else if(!Character.isWhitespace(str.charAt(i))){
throw new IllegalArgumentException( "Error in Function" );
}
}
}
if (firstDouble){firstInNumber = Double.parseDouble(firstInString);}else{firstInNumber = Integer.parseInt(firstInString);}
if (secondDouble){secondInNumber = Double.parseDouble(secondInString);}else{secondInNumber = Integer.parseInt(secondInString);}
set.add(firstInNumber);
set.add(secondInNumber);
set.add(op);
return set;
}
public static double getFirstParam(String st){
ArrayList<Object> g = parse(st);
return (Double)g.get(0);
}
public static double getSecondParam(String str){
ArrayList<Object> g = parse(str);
return (Double)g.get(1);
}
public static char getOperator(String str){
ArrayList<Object> g = parse(str);
return g.get(2).toString().charAt(0);
}
public static double calculate(String bla){
ArrayList<Object> g = parse(bla);
double first = (Double)g.get(0);
double second = (Double)g.get(1);
char oper = g.get(2).toString().charAt(0);
switch(oper) {
case '+':return first + second;
case '-':return first - second;
case '*':return first * second;
case '/':return first / second;
default: return 0.0;
}
}
}