简体   繁体   English

在java中使用charAt添加字符给我错误的总和

[英]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'的代码值是4857 ,所以您可以从每个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.

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