I am trying to write a String ie evaluation function
evaluate("4 + 1") ;
evaluate("4 + 1 + 3") ;
evaluate("4 + 1 * 3") ;
The operators are + - / and *
At first, I wanted to use regular expressions to collect operators and numbers, as they can be matched. And the later you find this information, somehow figure out a way to prioritize /*ove statements -+.
Here's 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 for extracting numbers 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 this is the part where I am stuck. # 1 This method described above fails in the third example:
evaluate("4 + 1 * 3") ; // returns 7 (not 15)
And this is # 2. Even if I try the previous examples, I cannot figure out how to place them correctly.
I'm on the right track at all, does anyone have any good advice, please share?
source