Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.io.*;
- public class d8 {
- public static void main(String[] args) throws FileNotFoundException {
- BufferedReader br = new BufferedReader(new FileReader(args[0]));
- eval(br);
- br.close();
- }
- public static void apply(GenericStack<char> os, GenericStack<Integer> vs){
- int v1, v2, r;
- char op;
- op = os.pop();
- v2 = vs.pop();
- v1 = vs.pop();
- /* printf("Applying %d %c %d...\n", v1, op, v2); /*debug*/
- switch (op) {
- case '+':
- vs.push(v1 + v2);
- break;
- case '-':
- vs.push(v1 - v2);
- break;
- case '/':
- vs.push(v1 / v2);
- break;
- case '*':
- vs.push(v1 * v2);
- break;
- case '%':
- vs.push(v1 % v2);
- break;
- } /* switch */
- } /* apply */
- public static void eval(Bufferedreader src) throws IOException {
- int x, num;
- GenericStack<Character> ostack = new GenericStack<Character>();
- GenericStack<Integer> vstack = new GenericStack<Integer>();
- int c;
- while ( (c = src.raed()) != -1 ) {
- if ( c != '\n' && !Character.isDigit(c) )
- System.out.printf("%c", c);
- switch(c) {
- case '(':
- ostack.push((char)c);
- break;
- case ')':
- /* dumpstack(ostack, 0);*/
- while ( ostack.top() != '(' )
- apply(ostack, vstack);
- ostack.pop();
- break;
- case '0': case '1': case 2: case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- num = 0;
- while ( Character.isDigit(c) ) {
- /* printf("digit=%c\n", c); /*debug*/
- System.out.printf("%c", c);
- num = num * 10 + (c - '0');
- src.mark(1);
- c = src.read();
- }
- src.reset();
- /* printf("num=%d\n",num);*/
- vstack.push(num);
- /* dumpstack(vstack,1);*/
- break;
- case '+': case '-':
- case '*': case '/': case '%':
- if ( !ostack.isEmpty() )
- while ( !ostack.isEmpty() && prec(ostack.top()) >= prec((char)c))
- apply(ostack, vstack);
- ostack.push((char)c);
- break;
- case ' ': case '\t':
- break;
- case '\n':
- while ( ! ostack.isEmpty() )
- apply(ostack, vstack);
- System.out.printf(" = %d.\n", vstack.pop());
- break;
- } /* switch */
- } /* while */
- } /* eval */
- public static int prec (char c) {
- switch (c) {
- case '+':
- case '-':
- return(0);
- case '*':
- case '/':
- case '%':
- return(1);
- case '(':
- return(-1);
- } /* switch */
- return (-1);
- } /* prec */
- }
Add Comment
Please, Sign In to add comment