Advertisement
Guest User

Reverse Polish Notation Stack Driver Demo V2

a guest
Oct 17th, 2017
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. // A.C. Silvestri
  2. // 10/16/17
  3. // CSC-220 Data Structures
  4. // Reverse Polish Notation Stack Driver Demo V2
  5. // Supports negative numbers
  6.  
  7. package chapter10.Stacks;
  8.  
  9. import java.util.Scanner;
  10.  
  11. public class RPN {
  12.     public static void main(String[] args) {
  13.  
  14.         StackOfIntegers0 stack = new StackOfIntegers0();
  15.         Scanner input = new Scanner(System.in);
  16.         while (input.hasNextLine()) {
  17.             String line = input.nextLine();
  18.             String tokens[] = line.split("\\s+");
  19.             for (int i = 0; i < tokens.length; i++) {
  20.                 char ch = tokens[i].charAt(0);
  21.                 if (Character.isDigit(ch)) {
  22.                     stack.push(Integer.parseInt(tokens[i]));
  23.                 }
  24.                 else if (ch == '+')
  25.                     if (tokens[i].length() == 1) {
  26.                         int a = stack.pop();
  27.                         int b = stack.pop();
  28.                         stack.push(b + a);
  29.                     }
  30.                     else {
  31.                         stack.push(Integer.parseInt(tokens[i]));
  32.                     }
  33.                 else if (ch == '-')
  34.                     if (tokens[i].length() == 1) {
  35.                         int a = stack.pop();
  36.                         int b = stack.pop();
  37.                         stack.push(b - a);
  38.                     }
  39.                     else {
  40.                         stack.push(Integer.parseInt(tokens[i]));
  41.                     }
  42.                 else if (ch == '*') {
  43.                     int a = stack.pop();
  44.                     int b = stack.pop();
  45.                     stack.push(b * a);
  46.                 }
  47.                 else if (ch == '/') {
  48.                     int a = stack.pop();
  49.                     int b = stack.pop();
  50.                     stack.push(b / a);
  51.                 }
  52.             }
  53.  
  54.             System.out.println("Answer = " + stack.pop());
  55.         }
  56.         input.close();
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement