Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Stack;
- import java.lang.reflect.Array;
- public class Calculator{
- /*
- * This is the main processing class. Gets an input stream as a
- * String, then creates a Parser object, and then calls convertToRPN
- * method to get a manageable form for it. Then we compute it. There
- * we do some checking to make the work safe and sane.
- */
- public static Double getResult(String opLine) throws BraNotEnough, OperandsNotEnough {
- /*
- * THis is the only method in this class which is visible. This
- * is very ugly, I think, but I don't know, how t get it better
- * yet. Maybe later...
- * */
- if(checkBras(opLine) > 0){
- throw new BraNotEnough("More left bras than right!");
- } else if(checkBras(opLine) < 0){
- throw new BraNotEnough("Less left bras than right!");
- }
- Parser workLine = new Parser(opLine);
- Stack<Double> opStack = new Stack<Double>();
- String[] operation = workLine.convertToRPN();
- int index;
- if( !(checkOps(operation) ) ){
- throw new OperandsNotEnough("There aren't enough operands!");
- }
- for(index = 0; index < Array.getLength(operation); index++){
- String temporary = operation[index];
- if(operation[index] == null){continue;}
- if( Operator.isOperator(temporary).booleanValue() ){
- int jndex;
- Double result;
- Double[] operands = new Double[Operator.getOperands(temporary)];
- for(jndex = 0; jndex < Operator.getOperands(temporary); jndex++){
- operands[jndex] = opStack.pop();
- }
- opStack.push( Operator.doOperation(temporary, operands) );
- } else{
- opStack.push( Double.valueOf(operation[index]) );
- }
- }
- return opStack.pop();
- }
- private static int checkBras(String check){
- /*
- * There must be the same number of opening and closing bras.
- * So we return their difference to throw the correct message.
- * */
- int left = 0, right = 0;
- int index;
- for(index = 0; index < check.length(); index++){
- if(check.charAt(index) == '('){
- left++;
- } else if(check.charAt(index) == ')'){
- right++;
- }
- }
- return left-right;
- }
- private static boolean checkOps(String[] checkThis){
- /*
- * The numbers are always equal the number of operators plus
- * one. So we can easily check them.
- * */
- int index, operators = 0, numbers = 0;
- for(index = 0; index < Array.getLength(checkThis); index++){
- try{
- if(Operator.isOperator(checkThis[index])){
- operators++;
- } else if( !( Double.isNaN( Double.valueOf( checkThis[index]) ) ) ){
- numbers++;
- }
- } catch(NullPointerException npe){
- /*
- * When there were bras, the converted array of strings
- * inhalts some null object at the end. This isn't error,
- * therefore we have to handle this case.
- * */
- return ( (numbers - operators) == 1 ) ? true : false;
- }
- }
- return ( (numbers - operators) == 1 ) ? true : false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement