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){
- char[]chars = here.toCharArray();
- 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;
- for(char c: chars)
- {
- //System.out.println("c is:" + c);
- if(Character.isDigit(c)){
- System.out.println("is a digit: " + c);
- Double.parseDouble(Character.toString(c));
- }
- else {
- operator = String.valueOf(c);
- nextCharacter = c;
- 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);
- }
- operatorstack.push(nextCharacter);
- 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