java - EmptyStack exception related to Postfix Evaluation -


the program should accept input user in form of postfix expression , evaluate it. need use array , char program due assignment requirement. problem i'm getting emptystackexception don't know why. need print final result evaluation.

here's code:

import java.util.*;  public class stackpostfixeva {     public static void main(string args[]) {         scanner key = new scanner(system.in);         char[] postfix = new char[10];         system.out.println("please enter postfix expression. "                 + "enter '#' if have finish entering postfix expression");         int i;         (i = 0; <= 9; i++) {             postfix[i] = key.next().charat(0);             if (postfix[i] == '#') {                 break;             }         }         system.out.println("the postfix expression are:");         (i = 0; <= 9; i++) {             system.out.println(postfix[i]);         }         stack<integer> st = new stack<>();         int result, ch1, ch2;         (i = 0; <= postfix.length; i++) {             if (postfix[i] >= '0' && postfix[i] <= '9') {                 st.push(postfix[i] - '0');             } else {                 ch1 = st.pop();                 ch2 = st.pop();                 switch (postfix[i]) {                 case '+':                     result = ch2 + ch1;                     break;                 case '-':                     result = ch2 - ch1;                     break;                 case '*':                     result = ch2 * ch1;                     break;                 case '/':                     result = ch2 / ch1;                     break;                 case '%':                     result = ch2 / ch1;                     break;                 default:                     result = 0;                 }                 st.push(result);             }         }         result = st.pop();         system.out.println(result);     } } 

sorry messy work , in advance helping me. ^_^

i don't see anywhere checking

if(st.isempty())  

also, why popping out 2 elements @ once , not checking empty stack ?

  else{  //execution if operator found     ch1 = st.pop();     ch2 = st.pop(); 

obviously, if there 1 element in stack , if next line execute throw exception.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -