2015-04-08 6 views
1

У меня возникли проблемы с выяснением логики динамического калькулятора infix. Я могу разместить строковые значения с 5 элементами, такими как «1 + 1», но я не могу вычислить строки с более чем 5 элементами (например: «1 + 2 + 3 + 4»).Логика калькулятора Java infix

Это мой процесс

import java.util.StringTokenizer; 

открытые статические INT высчитывает (String вход) { INT л.ш. = 0; int rhs = 0; int total = 0; char operation = '';

int intOne, intTwo; 

    StringTokenizer st = new StringTokenizer(input); 

    /* 
    * this block is chosen if there are no operations 
    */ 

    // block of if statement code for inputs less than or equal to 
    // 5 characters. 

     /* 
     * this block generates the correct number if there is more than 
     * one operator in the equation. 
     */ 

    }else if(input.length() > 5){ 
     int firstValue = 0; 
     int latterValue = 0; 

     while(st.hasMoreTokens()){ 
      /* 
      * method that assigns the left and right sides 
      */ 

      //assigns values to the first equation 
      int firstToken = Integer.parseInt(st.nextToken()); 
      String opToken = st.nextToken(); 
      int latterToken = Integer.parseInt(st.nextToken()); 

      //returns a value for the first equation 
      firstValue = assignSides(firstToken, opToken, latterToken); 

      // takes in the next operator 
      if(st.nextToken().equals("+")){ 
       operation = '+'; 
      }else if(st.nextToken().equals("-")){ 
       operation = '-'; 
      }else if(st.nextToken().equals("*")){ 
       operation = '*'; 
      }else if(st.nextToken().equals("/")){ 
       operation = '/'; 
      } 

      // assigns values to the latter equation 
      firstToken = Integer.parseInt(st.nextToken()); 
      opToken = st.nextToken(); 
      latterToken = Integer.parseInt(st.nextToken()); 

      //returns a value for the latter equation 
      latterValue = assignSides(firstToken, opToken, latterToken); 

      /* 
      * decides how to add the two equations 
      */ 
      switch(operation){ 
      case '+': total = firstValue + latterValue; 
      break; 
      case '-': total = firstValue - latterValue; 
      break; 
      case '*': total = firstValue * latterValue; 
      break; 
      case '/': total = firstValue/latterValue; 
      break; 
      default: System.out.println("cannot compute"); 
      break; 
      } 

      if(st.hasMoreTokens()){ 
       //makes the total the first value 
       total = firstValue; 

       if(st.nextToken().equals("+")){ 
        operation = '+'; 
       }else if(st.nextToken().equals("-")){ 
        operation = '-'; 
       }else if(st.nextToken().equals("*")){ 
        operation = '*'; 
       }else if(st.nextToken().equals("/")){ 
        operation = '/'; 
       } 
      } 
     } 
    } 
    return total; 
} 

public static int assignSides(int firstToken, String opToken, int latterToken) 
{ 
    int lhs=0; 
    int rhs = 0; 
    int sum = 0; 
    char operation = ' '; 

    /* 
    * converts the string into a character 
    */ 
    if(opToken.equals("+")){ 
     operation = '+'; 
    }else if(opToken.equals("-")){ 
     operation = '-'; 
    }else if(opToken.equals("*")){ 
     operation = '*'; 
    }else if(opToken.equals("/")){ 
     operation = '/'; 
    } 

    rhs = latterToken; 

    /* 
    * interprates the character as a function 
    */ 
    switch(operation){ 
    case '+': sum = lhs + rhs; 
    break; 
    case '-': sum = lhs - rhs; 
    break; 
    case '*': sum = lhs * rhs; 
    break; 
    case '/': sum = lhs/rhs; 
    break; 
    default: System.out.println("cannot compute"); 
    break; 
    } 

    return sum; 
} 

Могу ли я помочь мне с ошибкой в ​​моей логике?

+0

Это домашнее задание? Если вам разрешено использовать бинарные деревья? –

+0

Почему ваша граница 5 элементов? почему не 3 элемента, как в «1 + 1»? –

+0

@ Майкл Хоббс это упражнение, но я не уверен, что это такое, и я не знаю. Я не думаю, что это необходимо на основе моего уровня. (CSE 143). –

ответ

1

При расчете более трех символов (не считая пробелов), как в «1 + 2 + 3»,
вам нужно рассчитать в таком порядке: 1 + (2 + 3).

Вы должны разделить первую и оставшуюся часть «2 + 3» и передать оставшуюся часть методу вычисления снова. Что-то вроде:

int firstPart = ...; // evaluation of "1" 
int secondPart = calculate("2 + 3"); 

int total = firstPart + secondPart;