Infusion of Wormwood n Asfodel Infusion of Wormwood n Asfodel - 10 months ago 82
Java Question

Subtract int from char : possible lossy conversion int to char

I am trying to subtract int from char in a typical cryptography key question but I am running into the above mentioned error in the following statements:

char ch = (int)encrypted_message.charAt(i) + key[index];
if (ch > 122)
ch = (int)ch - 26;

array holds digits of the key and is of type

How do rotate the char successfully?

Please help!

Answer Source

int is bigger than char, but the result of your operation is typed int (which you're then storing in a char). So the compiler is warning you you might lose information storing an int value into a char variable.

Instead, ensure the result is a char, which is a bit of a pain because + and - with char values results in an int, so we have to cast:

char ch = (char)(encrypted_message.charAt(i) + key[index]);
if (ch > 122)
    ch = (char)(ch - 26);