Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // A.C. Silvestri
- // 10/16/17
- // CSC-220 Data Structures
- // Reverse Polish Notation Stack Driver Demo V2
- // Supports negative numbers
- package chapter10.Stacks;
- import java.util.Scanner;
- public class RPN {
- public static void main(String[] args) {
- StackOfIntegers0 stack = new StackOfIntegers0();
- Scanner input = new Scanner(System.in);
- while (input.hasNextLine()) {
- String line = input.nextLine();
- String tokens[] = line.split("\\s+");
- for (int i = 0; i < tokens.length; i++) {
- char ch = tokens[i].charAt(0);
- if (Character.isDigit(ch)) {
- stack.push(Integer.parseInt(tokens[i]));
- }
- else if (ch == '+')
- if (tokens[i].length() == 1) {
- int a = stack.pop();
- int b = stack.pop();
- stack.push(b + a);
- }
- else {
- stack.push(Integer.parseInt(tokens[i]));
- }
- else if (ch == '-')
- if (tokens[i].length() == 1) {
- int a = stack.pop();
- int b = stack.pop();
- stack.push(b - a);
- }
- else {
- stack.push(Integer.parseInt(tokens[i]));
- }
- else if (ch == '*') {
- int a = stack.pop();
- int b = stack.pop();
- stack.push(b * a);
- }
- else if (ch == '/') {
- int a = stack.pop();
- int b = stack.pop();
- stack.push(b / a);
- }
- }
- System.out.println("Answer = " + stack.pop());
- }
- input.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement