Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.Stack;
- import java.lang.*;
- public class Infix {
- public static double calculations(String here) {
- Scanner input = new Scanner(System.in);
- MyStack<Character> operatorstack = new MyStack<Character>();
- MyStack<Double> valuestack = new MyStack<Double>();
- String operator;
- char topOperator;
- char nextCharacter;
- double operandTwo;
- double operandOne;
- double result;
- double next;
- while(input.hasNext())
- {
- if(input.hasNextDouble() ){
- next = input.nextDouble();
- valuestack.push(next);
- }
- else {
- operator = input.next();
- nextCharacter = operator.charAt(0);
- switch(nextCharacter) {
- case '^':
- operatorstack.push(nextCharacter);
- break;
- case '+':
- case '-':
- case '*':
- case '/':
- while(!operatorstack.isEmpty()&& getPriority(nextCharacter) <= getPriority(operatorstack.peek()))
- {
- // Calculate operator at the top of the stack.
- topOperator = operatorstack.pop();
- operandTwo = valuestack.pop();
- operandOne = valuestack.pop();
- if (topOperator == '*')
- result = operandOne * operandTwo;
- else if (topOperator == '/')
- result = operandOne / operandTwo;
- else if (topOperator == '+')
- result = operandOne + operandTwo;
- else if (topOperator == '-')
- result = operandOne - operandTwo;
- else
- throw new RuntimeException("You can't do that, illegal operator: " + topOperator);
- valuestack.push(result);
- topOperator = operatorstack.pop();
- }
- break;
- default:
- break;
- }
- }
- while(!operatorstack.isEmpty()){
- topOperator = operatorstack.pop();
- operandTwo = valuestack.pop();
- operandOne = valuestack.pop();
- if (topOperator == '*')
- result = operandOne * operandTwo;
- else if (topOperator == '/')
- result = operandOne / operandTwo;
- else if (topOperator == '+')
- result = operandOne + operandTwo;
- else if (topOperator == '-')
- result = operandOne - operandTwo;
- else
- throw new RuntimeException("You can't do that, illegal operator: " + topOperator);
- valuestack.push(result);
- }
- double answer = valuestack.peek();
- return answer;
- }
- }
- public static int getPriority(char nextCharacter) {
- if (nextCharacter == '*' || nextCharacter == '/')
- return 1;
- else if (nextCharacter == '+' || nextCharacter == '-')
- return 2;
- else if (nextCharacter == '=')
- return 3;
- else
- return Integer.MIN_VALUE;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement