0

I'm trying to solve a postfix expression using a char based stack.
I need to push some negative values into my char based stack such as '-2' but it stores only the '-' part.
My exact code looks like this-

             char val=Character.forDigit(operation(temp),10);
             System.out.println("pushed is "+val);


Output is "pushed is - "
Kindly help.

Shivam Aggarwal
  • 734
  • 2
  • 9
  • 23
  • 1
    -2 is two characters, which is why you only see the first character pushed. – pczeus Feb 13 '16 at 19:02
  • If you treat your stack as numbers, try `short` - [also 16 bits, like char, but signed.](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html). – Kenney Feb 13 '16 at 19:03

2 Answers2

1

Character class is singular. As in one character, one digit, so it's only getting the first of '-2'.

See this for a fuller explanation: Difference between "char" and "String" in Java

Community
  • 1
  • 1
Lindsay Ryan
  • 433
  • 3
  • 9
1

char means that it consists of 1 character from supported characters in any specific language. -2 isn't 1 character, its a string because it consist of sequence of characters e.g., '-' and '1'. So what your code is doing is doing the right thing.

Now, given that you really need characters to store your digits, then you have to map your negative value on to some other characters. Digits from 0..9 are actually ascci # 48..57. So what you can do is pic 10 consecutive characters from the ascci table and treat them as -ve. Lets say you pick a .. i as your -ve numbers then a = -1, b = -2 and so on ...

Keep in mind that since you are using character, you can't deal with two digit numbers as long as you treat each number as an individual character. Then you have to handle all "decimal" operations.

Em Ae
  • 8,167
  • 27
  • 95
  • 162
  • Thanks alot. That seems alot logical but if I use 'a' say for '-1' then how can I use it to do postfix operations. Do I need to create a separate mapping using switch cases for all the possible cases. If yes, then how will I distinguish between a positive number and negative number. – Shivam Aggarwal Feb 13 '16 at 19:10