Advertisement
Guest User

Untitled

a guest
Mar 29th, 2015
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. public static int evalDigit() throws InvalidExpression{
  2.                                                                                     // expects e[i] to be a digit
  3.                                                                                     // returns the int value of the digit
  4.                                                                                     // advances i to the position after the digit
  5.         if (e[i]>='0' && e[i]<='9'){
  6.           int result = e[i]-(int)'0';                                                // code for characters '0' to '9' are 48 to 57
  7.           i++;
  8.           return result;
  9.         } else {
  10.           throw new InvalidExpression("index "+i);
  11.         }
  12.       }
  13.      
  14.                                                                                     // YOU WILL MODIFY THIS METHOD TO WORK WITH TERMS BASED ON PARENTHESES
  15. public static int evalTerm() throws InvalidExpression{
  16.                                                                                     //returns the value of the term starting at index i
  17.                                                                                     //for simple expressions, a term is a single digit
  18.             return evalDigit();
  19.       }
  20.      
  21. public static int evalExpr() throws InvalidExpression {
  22.                                                                                     //evaluate the simple expression in the char array e
  23.         int result=evalTerm();
  24.         while (e[i]=='+' || e[i]=='-'){
  25.           switch (e[i]){
  26.             case '+':
  27.               i++;
  28.               result += evalTerm();
  29.               break;
  30.             case '-':
  31.               i++;
  32.               result -= evalTerm();
  33.               break;
  34.           }
  35.         }
  36.         return result;
  37.       }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement