Advertisement
artabetes

RPN Calculator

May 9th, 2020
775
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.58 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3. public class RPN {
  4.    
  5.     /**
  6.      * Get a filename from the user.
  7.      *
  8.      * @return User specified filename
  9.      */
  10.     public static String getFilename() {
  11.  
  12.         // Display message asking user for a filename.
  13.         // Read in the filename and return the filename.
  14.  
  15.         Scanner keyboard = new Scanner(System.in);
  16.  
  17.         // Filename entered by user
  18.         String fileName;
  19.  
  20.         System.out.println("Enter a filename.");
  21.  
  22.         fileName = keyboard.nextLine();
  23.  
  24.         // Close scanner object
  25.         keyboard.close();
  26.  
  27.         return fileName;
  28.     }
  29.    
  30.    
  31.     /**
  32.      * Create array to use in implementation of a stack.
  33.      *
  34.      * @param fileName User specified filename
  35.      * @throws IOException
  36.      */
  37.     public static String[] createBackingArray(String fileName) throws IOException {
  38.  
  39.         // Object to read text file
  40.         Scanner readTextFile = null;
  41.  
  42.         // Array to temporarily hold tokenized lines
  43.         // as they are read from a text file.
  44.         String[] tokens = null;
  45.  
  46.         // Read text tile in and tokenize each line.
  47.         try {
  48.             readTextFile = new Scanner(new File(fileName));
  49.  
  50.             while (readTextFile.hasNext()) {
  51.  
  52.                 tokens = readTextFile.nextLine().trim().split(",");
  53.             }
  54.  
  55.             // Display message to indicate file successfully read
  56.             //System.out.println("File read.");
  57.  
  58.         }
  59.  
  60.         // Throw exception and terminate if file not found etc.
  61.         catch (IOException ex) {
  62.             System.out.println("File not found. Program will terminate.");
  63.  
  64.             System.exit(0);
  65.         }
  66.  
  67.         // Returns array of tokenized lines from text file
  68.         return tokens;
  69.  
  70.     }
  71.    
  72.     /**
  73.      * Checks if a string is one of these operators( ^, +, -, *, /)
  74.      * @param str String from tokenized array.
  75.      * @return True if the string matches one of the operators in the conditional statement.
  76.      */
  77.     public static boolean checkIfOperator(String str) {
  78.         return(str.equals("^") || str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/"));
  79.     }
  80.    
  81.     /**
  82.      * Performs calculations based on operator and numbers provided.
  83.      * @param numOne
  84.      * @param numTwo
  85.      * @param operator
  86.      * @return The result of the calculation
  87.      */
  88.     public static int calculator(int numOne, int numTwo, String operator, Stack<String> numStack) {
  89.        
  90.         //Store result
  91.         int result = 0;
  92.        
  93.        
  94.         switch(operator) {
  95.         case "+":
  96.             numStack.push(Integer.toString(result = numOne + numTwo));
  97.             break;
  98.         case "-":
  99.             numStack.push(Integer.toString(result = numOne - numTwo));
  100.             break;
  101.         case "*":
  102.             numStack.push(Integer.toString(result = numOne * numTwo));
  103.             break;
  104.         case "/":
  105.             numStack.push(Integer.toString(result = numOne / numTwo));
  106.             break;
  107.         case "^":
  108.             numStack.push(Integer.toString(result = numOne ^ numTwo));
  109.             break;
  110.         }
  111.         return result;
  112.     }
  113.    
  114.     /**
  115.      * Performs calculations using reverse polish notation.
  116.      * @param tokens Array of operators and operands
  117.      * @return Value on top of given stack
  118.      * @throws IOException
  119.      */
  120.    
  121.     public static String rpnCalculator(String [] tokens) throws IOException{
  122.        
  123.         //Check if array is empty before proceeding
  124.         //If array is empty get filename from user and create array
  125.         if(tokens == null || tokens.length == 0) {
  126.             System.out.println("Error. Data has not been stored.");
  127.            
  128.             createBackingArray(getFilename());
  129.         }
  130.        
  131.         //Store values as strings in stack
  132.         Stack<String> numStack = new Stack<String>();
  133.        
  134.         //Result of calculations
  135.         String result = null;
  136.        
  137.         int operandTwo = 0;
  138.         int operandOne = 0;
  139.        
  140.         //Holds operators
  141.         String operator = null;
  142.            
  143.         //If value is an operator pop two values from stack and perform calculations
  144.         for(int index = 0; index < tokens.length; index++) {
  145.            
  146.             //Push values to stack
  147.             numStack.push(tokens[index]);
  148.         }
  149.             for(int index = 0; index < tokens.length; index++) {
  150.             if(checkIfOperator(tokens[index])){
  151.                
  152.                 //If an operator, pop from stack to use in calculation
  153.                 operator = numStack.pop();
  154.                
  155.                 //Convert values to ints
  156.                 //operandOne is on the left of operator, operandTwo is on the right
  157.                  operandTwo = Integer.parseInt(numStack.pop());
  158.                  operandOne = Integer.parseInt(numStack.pop());
  159.                
  160.                  //Convert to string
  161.                   result = Integer.toString(calculator(operandOne, operandTwo, operator, numStack));
  162.                
  163.                
  164.             }
  165.            
  166.             //System.out.println(numStack.peek());
  167.             }  
  168.          return numStack.pop();
  169.          }
  170.    
  171.  
  172.     public static void main(String[] args) throws IOException {
  173.        
  174.         //Holds values from text file in an array
  175.         String [] valuesFromFile = createBackingArray(getFilename());
  176.        
  177.         //Displays results of calculations to user
  178.         System.out.println(rpnCalculator(valuesFromFile));
  179.        
  180.        
  181.     }
  182.  
  183. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement