简体   繁体   中英

How to perform ASCII subtraction in java

I've got a char[] array named temp which only contains a , b or c . Now if the two adjacent characters in the array are distinct, ie temp[j] and temp[j+1] contains a and b respectively, I need to store c in temp[j+1] .

And for that, I defined,

private static final int CHARSUM = 294;

which is the sum of ASCII value of a , b and c . and what I tried was to subtract the sum of temp[j] and temp[j+1] from 294 .

temp[j+1] = CHARSUM-(temp[j]+temp[j+1]);

which should store the value c if the other values were a and b . But here, the problem is:

incompatible types: possible lossy conversion from int to char

And I tried changing to:

  • private static final char CHARSUM = "294";
  • temp[j+1] = (char)CHARSUM-(temp[j]+temp[j+1]);
  • temp[j+1] = Character.getNumericValue(CHARSUM-(temp[j]+temp[j+1]));

However, none of those did work and I did not find any other answers that would help me to solve the problem. So Any help to fix this will be highly appreciated. Thanks.

您可以将减法的结果转换为char:

temp[j+1] = (char)(CHARSUM-(temp[j]+temp[j+1]));

In Java, a char is "really" a whole number between 0 and 65535 . If you want to assign an int outside that range to a char variable, an explicit cast is required.

For example

char c = 65535;        // ok
char c = 65536;        // doesn't compile
char c = (char) 65536; // compiles, but it's a lossy conversion

Even though for your values, CHARSUM-(temp[j]+temp[j+1]) is always in that range, the compiler can't tell that because it is not a compile time constant. Therefore you need to apply a cast to the entire expression:

temp[j+1] = (char) (CHARSUM-(temp[j]+temp[j+1]));

Your approaches did not work, for reasons I'll explain:

  • "294" is a String , not an int .
  • The cast is only applied to CHARSUM - the entire expression is still an int .
  • getNumericValue returns an int not a char , so you'd have to cast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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