casting experts please help me out here

publicint value(){

int result = 0;

String temp =12+

Stack<Character> s =new Stack<Character>();

for (int i = 0; i<temp.length(); i++){

char c = temp.charAt(i);

if (c !='+' && c !='-' && c !='/' && c !='%' && c !='*' && c!='(' & c!=')'){

s.push(c);

System.out.println(s.peek());

}

elseif (c =='+' || c =='-' || c =='/' || c =='%' || c =='*'){

int right = s.pop();

int left = s.pop();

result += (int)left + c + (int)right;

s.push((char)result);

}

}

return result;

}

on the print statement:

System.out.println(s.peek());

it gives me 1 and 2 but when I pop it out of the stack it gives me 50 and 49. How do I solve this? This is really weird because when peeking and popping it gives the different result>

[1985 byte] By [aditya15417a] at [2007-11-26 20:02:39]
# 1

Hi,

I guess you are popping the stack and assigning the popped value to an "int". Since the stack contains "Character" objects, when you pop the Character objects corresponding to '1' and '2' and assign it to "int", you will get the ASCII equivalents of '1' and '2', namely 49 and 50.

Hence, you must assign the popped values to "char" rather than "int".

int right = s.pop();

int left = s.pop();

must be replaced with

char right = s.pop();

char left = s.pop();

//Convert the characters to integers

int rightVal = Integer.parseInt("" + right);

int leftVal = Integer.parseInt("" + left);

//Do subsequent processing with these int values

By the way, I think you are trying to evaluate a post-fix expression in this code. It has got compilation errors as well as logical flaws. For eg; After you encounter an operator like '+' or '-', you must make a switch on that character, and perform addition or subtraction accordingly.

Regards,

Kumar.

kumar_iyera at 2007-7-9 23:02:01 > top of Java-index,Java Essentials,Java Programming...
# 2
hey kumar you answered this question on the other topic that I also posted, you said that there were some other logical flaws in my code. can you show it to me where it is besides the one that you have showed me?
aditya15417a at 2007-7-9 23:02:01 > top of Java-index,Java Essentials,Java Programming...
# 3
This might be problem...What ur getting is ascii value so just work on the so that it will print the value you want and not the ascii...Thanks
SUSHANT_Ja at 2007-7-9 23:02:01 > top of Java-index,Java Essentials,Java Programming...