본문 바로가기
Program/Java

Java RPN Calculator

by pishio 2022. 6. 17.
import java.util.Scanner;
import java.util.Stack;

public class RPNCalculator {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String inputStr = scanner.nextLine();
        System.out.println(inputStr);


        Stack<String> stack = stringToStack(inputStr);
        int answer = calculatePostfix(stack);
        System.out.println(answer);

    }

    public static Stack<String> stringToStack(String input) {
        String[] inputs = input.split(" ");
        Stack<String> stack = new Stack<String>();

        for (int i = 0; i < inputs.length; i++) {
            stack.push(inputs[i]);
        }
        return stack;
    }

    public static int calculatePostfix(Stack<String> stack) {

        String strValue = stack.pop();
        int calculatedValue, newValue;
        try {
            calculatedValue = Integer.parseInt(strValue);
        } catch (Exception e) {
            newValue = calculatePostfix(stack);
            calculatedValue = calculatePostfix(stack);
            calculatedValue = getCalculatedValue(strValue, calculatedValue, newValue);
        }
        return calculatedValue;
    }

    private static int getCalculatedValue(String strValue, int calculatedValue, int newValue) {
        if (strValue.equals("+")) calculatedValue += newValue;
        else if (strValue.equals("-")) calculatedValue -= newValue;
        else if (strValue.equals("*")) calculatedValue *= newValue;
        else if (strValue.equals("/")) calculatedValue /= newValue;
        return calculatedValue;
    }
}

'Program > Java' 카테고리의 다른 글

Predicate in stream  (0) 2022.07.01
@ParameterizedTest with array list  (0) 2022.06.29
[JUnit] assertTrue(), assertFalse()  (0) 2022.06.15

댓글