Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int evalDigit() throws InvalidExpression{
- // expects e[i] to be a digit
- // returns the int value of the digit
- // advances i to the position after the digit
- if (e[i]>='0' && e[i]<='9'){
- int result = e[i]-(int)'0'; // code for characters '0' to '9' are 48 to 57
- i++;
- return result;
- } else {
- throw new InvalidExpression("index "+i);
- }
- }
- // YOU WILL MODIFY THIS METHOD TO WORK WITH TERMS BASED ON PARENTHESES
- public static int evalTerm() throws InvalidExpression{
- //returns the value of the term starting at index i
- //for simple expressions, a term is a single digit
- return evalDigit();
- }
- public static int evalExpr() throws InvalidExpression {
- //evaluate the simple expression in the char array e
- int result=evalTerm();
- while (e[i]=='+' || e[i]=='-'){
- switch (e[i]){
- case '+':
- i++;
- result += evalTerm();
- break;
- case '-':
- i++;
- result -= evalTerm();
- break;
- }
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement