Skip to content

Instantly share code, notes, and snippets.

@rshepherd
Last active December 30, 2015 02:29
Show Gist options
  • Save rshepherd/7762838 to your computer and use it in GitHub Desktop.
Save rshepherd/7762838 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
public class ExpressionParser {
public static void main(String[] arg) {
// Assume the entered expression has only the expected characters otherwise they are ignored
String input = "(400+8) * (6-5)/((311-2) *(2+2)) xxx";
// Parse input
List<String> infix = parse(input.toCharArray());
// Print the output
for(String element : infix) {
System.out.print(element + " ");
}
}
private static List<String> parse(char[] input) {
List<String> parsed = new ArrayList<String>();
for (int i = 0; i < input.length; ++i) {
char c = input[i];
if (Character.isDigit(c)) {
String number = input[i] + "";
for (int j = i + 1; j < input.length; ++j) {
if (Character.isDigit(input[j])) {
number += input[j];
i = j;
} else {
break;
}
}
parsed.add(number);
} else if (c == '*' || c == '/' ||
c == '+' || c == '^' ||
c == '-' || c == '(' || c == ')') {
parsed.add(c + "");
}
// else ignore other characters
}
return parsed;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment