简体   繁体   English

如何将负整数转换为char数据类型

[英]How to convert a negative integer value into char datatype

I'm trying to solve a postfix expression using a char based stack. 我正在尝试使用基于char的堆栈来解决后缀表达式。
I need to push some negative values into my char based stack such as '-2' but it stores only the '-' part. 我需要将一些负值压入基于char的堆栈中,例如'-2'但它仅存储'-'部分。
My exact code looks like this- 我的确切代码如下所示:

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


Output is "pushed is - " 输出为"pushed is - "
Kindly help. 请帮助。

Character class is singular. 字符类是单数。 As in one character, one digit, so it's only getting the first of '-2'. 就像一个字符一样,一个数字,因此只能得到“ -2”的第一个字符。

See this for a fuller explanation: Difference between "char" and "String" in Java 请参阅此内容以获得更完整的解释: Java中“ char”和“ String”之间的区别

char means that it consists of 1 character from supported characters in any specific language. char表示它由任何特定语言的受支持字符中的1个字符组成。 -2 isn't 1 character, its a string because it consist of sequence of characters eg, '-' and '1' . -2不是1个字符,而是一个string因为它由字符序列组成,例如'-''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 . 0..9数字实际上是ascci# 48..57 So what you can do is pic 10 consecutive characters from the ascci table and treat them as -ve. 因此,您可以做的是从ascci表中连续图片10个字符,并将它们视为-ve。 Lets say you pick a .. i as your -ve numbers then a = -1, b = -2 and so on ... 假设您选择一个.. i作为您的-ve数字,然后a = -1,b = -2,依此类推...

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. 然后,您必须处理所有“十进制”操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM