Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.Scanner;
- public class Main {
- public static class Calculator{
- public static String toRPN(String expr){//перевод в польскую нотацию
- String current = "";
- Stack<Character> stack = new Stack<>();
- int priority;
- for (int i = 0; i < expr.length(); i++){
- priority = getP(expr.charAt(i));
- if (priority == 0){
- current += expr.charAt(i);
- }
- if (priority == 1) stack.push(expr.charAt(i));
- if (priority > 1){
- current += ' ';
- while (!stack.empty()){
- if (getP(stack.peek()) >= priority) {
- current += stack.pop();
- current += ' ';
- }
- else {
- break;
- }
- }
- stack.push(expr.charAt(i));
- }
- if (priority == -1){
- //current += ' ';
- while (getP(stack.peek()) != 1) {
- current += ' ';
- current += stack.pop();
- }
- stack.pop();
- }
- }
- current += ' ';
- while (!stack.empty()) {
- current += stack.pop();
- current += ' ';
- }
- return current;
- }
- public static int Answer(String rpn){//ответ
- String operand = new String();
- Stack<Integer> stack = new Stack<>();
- for (int i = 0; i < rpn.length(); i++){
- if (rpn.charAt(i) == ' ') continue;
- if (getP(rpn.charAt(i)) == 0){
- while (rpn.charAt(i) != ' ' && getP(rpn.charAt(i)) == 0){
- operand += rpn.charAt(i++);
- if (i == rpn.length()) break;
- }
- stack.push(Integer.parseInt(operand));
- operand = new String();
- }
- if (getP(rpn.charAt(i)) > 1){
- int a = stack.pop(), b = stack.pop();
- if (rpn.charAt(i) == '+') stack.push(b+a);
- if (rpn.charAt(i) == '-') stack.push(b-a);
- if (rpn.charAt(i) == '*') stack.push(b*a);
- if (rpn.charAt(i) == '/') stack.push(b/a);
- }
- }
- return stack.pop();
- }
- private static int getP(char token){//приоритет операторов
- if (token == '*' || token == '/') return 3;
- else if (token == '+' || token == '-') return 2;
- else if (token == '(') return 1;
- else if (token == ')') return -1;
- else return 0;
- }
- }
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- String str = sc.nextLine();
- System.out.println("Expression:");
- System.out.println(str);
- System.out.println("Reverse Polish Notation:");
- System.out.println(Calculator.toRPN(str));
- System.out.println("Result:");
- System.out.println(Calculator.Answer(Calculator.toRPN(str)));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement