Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package rpn;
- import java.io.*;
- import java.util.*;
- public class RPN {
- private Stack stack = new Stack();
- private Queue <Character> output = new LinkedList<>();
- private Integer result = new Integer(-1);
- private Scanner scanner;
- private HashMap<Character, Integer> operators = new HashMap<Character, Integer>();
- // converting to RPN
- private void convert() throws IOException {
- // opening
- scanner = new Scanner(new File("C:/Users/Dominika/source/repos/onp/src/files/calculations.txt"));
- initPriority();
- // if file exists, read a char
- char read = 0;
- int counter = 0;
- while (scanner.hasNext()) {
- read = (char) scanner.next().charAt(counter);
- counter++;
- if (Character.isDigit(read)) {
- output.add(read);
- } else if (isFunction(read)) {
- stack.push(read);
- } else if (isOperand(read)) {
- checkOperand(read);
- }
- }
- while (!stack.empty()) {
- output.add((char) stack.peek());
- stack.pop();
- }
- // closing
- scanner.close();
- }
- private void checkOperand(char read) {
- if (read == '+' || read == '-') {
- if ((char) stack.peek() == '*' || (char) stack.peek() == '/') {
- output.add((char) stack.peek());
- stack.pop();
- checkOperand(read);
- }
- } else {
- stack.push(read);
- }
- }
- private void initPriority() {
- operators.put('*', 3);
- operators.put('/', 3);
- operators.put('+', 1);
- operators.put('-', 1);
- }
- private boolean isOperand(char c) {
- if (c == '+' || c == '-' || c == '*' || c == '/') {
- return true;
- } else return false;
- }
- private boolean isFunction(char c) {
- if (c == 's' || c == 't' || c == 'c') {
- return true;
- } else return false;
- }
- public static void main(String[] args) throws IOException {
- RPN rpn = new RPN();
- rpn.convert();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement