Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. package rpn;
  2.  
  3. import java.io.*;
  4. import java.util.*;
  5.  
  6. public class RPN {
  7.  
  8. private Stack stack = new Stack();
  9. private Queue <Character> output = new LinkedList<>();
  10. private Integer result = new Integer(-1);
  11. private Scanner scanner;
  12. private HashMap<Character, Integer> operators = new HashMap<Character, Integer>();
  13.  
  14. // converting to RPN
  15. private void convert() throws IOException {
  16. // opening
  17. scanner = new Scanner(new File("C:/Users/Dominika/source/repos/onp/src/files/calculations.txt"));
  18. initPriority();
  19.  
  20. // if file exists, read a char
  21. char read = 0;
  22. int counter = 0;
  23. while (scanner.hasNext()) {
  24. read = (char) scanner.next().charAt(counter);
  25. counter++;
  26. if (Character.isDigit(read)) {
  27. output.add(read);
  28. } else if (isFunction(read)) {
  29. stack.push(read);
  30. } else if (isOperand(read)) {
  31. checkOperand(read);
  32. }
  33. }
  34.  
  35. while (!stack.empty()) {
  36. output.add((char) stack.peek());
  37. stack.pop();
  38. }
  39.  
  40. // closing
  41. scanner.close();
  42. }
  43.  
  44. private void checkOperand(char read) {
  45. if (read == '+' || read == '-') {
  46. if ((char) stack.peek() == '*' || (char) stack.peek() == '/') {
  47. output.add((char) stack.peek());
  48. stack.pop();
  49. checkOperand(read);
  50. }
  51. } else {
  52. stack.push(read);
  53. }
  54. }
  55.  
  56. private void initPriority() {
  57. operators.put('*', 3);
  58. operators.put('/', 3);
  59. operators.put('+', 1);
  60. operators.put('-', 1);
  61. }
  62.  
  63. private boolean isOperand(char c) {
  64. if (c == '+' || c == '-' || c == '*' || c == '/') {
  65. return true;
  66. } else return false;
  67. }
  68.  
  69. private boolean isFunction(char c) {
  70. if (c == 's' || c == 't' || c == 'c') {
  71. return true;
  72. } else return false;
  73. }
  74.  
  75. public static void main(String[] args) throws IOException {
  76. RPN rpn = new RPN();
  77. rpn.convert();
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement