1
votes

I'm doing some code for school, the exercise is: to do the Caesar cipher. The code:

char temp = 'u';
int key = 14; 
int tempInt = ((int) temp) + key;
temp = (char) tempInt;

The temp should be 132 (ASCII) but java gives me '?'. How can I resolve this problem? I think that Java is working in Unicode... but I don't know how to do my exercise with adding the key value to the text (Caesar cipher).

1
tempInt should contain the value you're after, temp contains a char which has the value of tempInt. - Mark
Also, there is no ASCII character with the value 131 (or 132, as you call it). That shouldn't matter though (as the system doesn't restrict itself to ASCII), but \u0083 is not a printable character. - Mr Lister

1 Answers

3
votes

With you code temp is 131 which is not a printable char In order to do Cesare cipher, you should probably work only on pritable chars (basically from 32 to 127. So you should be using modulo, so that 127+1 gives you 32

What you need to define is the range of char you handle (maybe only from 'a' to 'z') and then identify the size of this range.

Example with 32 and 127 :

char temp = 'u';
int key = 14;
int tempInt = ((int) temp) + key;
tempInt -= 32;
tempInt %= (127 - 32);
tempInt += 32;
temp = (char) tempInt;
System.out.println(temp);