I'm trying to write a String evaluation function i.e.
evaluate("4 + 1") ; // returns 5
evaluate("4 + 1 + 3") ; // returns 8
evaluate("4 + 1 * 3") ; // returns 7 (not 15)
The operators are + - / and *
My initial though was to use regular expressions to collect operators and digits as these can be matched. And than after finding that info, somehow figure out a way to prioritize /*
ove -+
operators.
Here is how I started :
static String regex = "([\\+\\*-/])+";
static String digitRegex = "(\\d)+";
public static void main(String[] args) {
System.out.println(getOperators("4 + 1 * 3"));
}
public static List<String> getOperators(String input) {
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(input);
List<String> operatorList = new ArrayList<String>();
int count = 0;
while (matcher.find()){
if (matcher.group(count) != null && matcher.group(count).trim().length() > 0) {
operatorList.add(matcher.group(count));
count++;
}
}
return operatorList;
}
Now I can write another method to extract the digits using the same logic.
public static List<Integer> getDigits(String input) {
Pattern p = Pattern.compile(digitRegex);
Matcher matcher = p.matcher(input);
List<Integer> digitList = new ArrayList<Integer>();
int count = 0;
while (matcher.find()) {
if (matcher.group(count) != null && matcher.group(count).trim().length() > 0) {
digitList.add(Integer.valueOf(matcher.group(count)));
count++;
}
}
return digitList;
}
Now is the part where I'm stuck. #1 This above method fails on the third example :
evaluate("4 + 1 * 3") ; // returns 7 (not 15)
And this #2 Even if I try previous examples, I can't figure it out how to put them in the correct order.
Am I on the right track at all, does anyone have some useful advice please share?