Last active
December 30, 2015 02:29
-
-
Save rshepherd/7762838 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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