-2

Im having trouble extracting the String data from a stack and converting it to int to perform arithmetic, it keeps telling me that i cannot cast a string to an int and vice versa, however i don't know any other alternative methods. this is the code i have:

int t1 = Integer.parseInt((String)stk.pop());
int t2 = Integer.parseInt((String)stk.pop());

int z;
switch(current)    {
    case '+': 
         z = t2 + t1;
        break;

    case '-':
        z = t2 -t1;
        break;

    case '*':
        z =  t2 * t1;
        break;

    case '/': 
        z =  t2 / t1;
        break;

    default: z = 0;

}

stk.push(z);
if(!moreSymbols.hasNext()) {
    String result = (String)stk.pop();
}
George Brighton
  • 5,131
  • 9
  • 27
  • 36
  • exactly what is your problem or what specifically is failing? – Chris Knight Nov 06 '13 at 14:08
  • can you add the code for your method "pop" ? – Ankit Rustagi Nov 06 '13 at 14:08
  • Why aren't you using `Integer.parseInt(String)` as you did in the top of your code? – Mureinik Nov 06 '13 at 14:12
  • stk refers to: Stack stk = new Stack(); – user2904913 Nov 06 '13 at 14:19
  • The question is how to pop the string contents that already is contained inside the stack and convert them to integers to pergorm arithmetic. The above code throws an error which says that Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at stackFile.evaluateRPN(stackFile.java:252) <---- refers to the line containing int t2 – user2904913 Nov 06 '13 at 14:21

2 Answers2

1

You have String objects on your stack and later on you are pushing onto stack calculation result whitch is int.Now, you are trying to pop your result (int) as a String in line String result = (String)stk.pop(); I suggest to either keep your data on stack as integers, or simply swap stk.push(z); into this stk.pust(String.valueOf(z));

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

On this line you are pushing an integer onto the stack:

stk.push(z);

Consequently, it will fail later when you try to pop a String. If everything else on it must be a String, make sure you push a String back:

stk.push(String.valueOf(z));

If this "Stack" class is java.util.Stack, or is a another class supporting generics, you can save yourself some trouble by telling the compiler that this stack is restricted to strings when you declare it:

Stack<String> stk = new Stack<>();

Then the compiler will prevent you from accidentally pushing an integer, and you won't need to manually cast to String on pop. See the tutorial on Generics for more explanation.

Boann
  • 48,794
  • 16
  • 117
  • 146