[英]adding characters using charAt in java is giving me the wrong sum
int x=(int)compressedText.charAt(one1+1);
int y=(int)compressedText.charAt(one1+2);
count=x+y;
count1=(char)count;
the craracter value for compressedText.charAt(one1+2) and compressedText.charAt(one1+1) are each equal to 1 but when I try to debug my code it says count is equal to 98. CompressedText.charAt(one1 + 2)和compressedText.charAt(one1 + 1)的抓取值分别等于1,但是当我尝试调试代码时,它说count等于98。
Casting a char
that represents a numeric character to an int
doesn't do what you think it does. 将表示数字字符的char
强制转换为int
并不会像您认为的那样工作。 It takes the Unicode value of the char
(which is 49
for '1'
). 它采用char
的Unicode值( '1'
为49
)。 That explains why you get 98
instead of 2
. 这就解释了为什么得到98
而不是2
。
Because the code values for the characters '0'
through '9'
are 48
through 57
, you can subtract '0'
( 48
) from each char
instead, eg 因为字符'0'
到'9'
的代码值是48
到57
,所以您可以从每个char
减去'0'
( 48
),例如
int x = compressedText.charAt(one1+1) - '0';
You'll need to undo this conversion if you are converting an int
back to a char
that is meant to represent the numeric character. 如果要将int
转换回表示数字字符的char
,则需要撤消此转换。 Also you'll need to account for multiple characters if count
is more than one digit (>= 10). 另外,如果count
超过一位数字(> = 10),则需要考虑多个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.