I'm not sure that A to Z, B to C
corresponds to a Caesar Shift does it?
Let's take the example from Wikipedia, a left shift of 3 places, or equivalently a right shift of 23 places:
Plain: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Cipher: XYZABCDEFGHIJKLMNOPQRSTUVW
To get the position of the cipher character we add the right shift, 23
, to the position of the plain character. This is fine for A,B,C
, but by the time we get to D
we've gone beyond the end of the alphabet. To fix this we need to "wraparound" to the beginning, and the technique for doing this is to use the modulo (%)
operator, with a modulus equal to the number of elements, in this case 26. You said you just wanted a nudge, so hopefully this is enough, but not too much, information.
One more point. You say you're code is outputting 0 for 'A'
, 1 for 'B'
etc. With 'A'
as input your code is equivalent to:
System.out.print ((char)('A'+'A'+26) % 26)
'A' has an integer value of 65, so this is equivalent to:
System.out.print ((char)(65+65+26) % 26)
You're casting (65+65+26)
to a char
, but then the %
operator, with an int
operand (26)
, produces an int
, so you're actually printing:
System.out.print (0)
Once you've worked out the correct expression
for the Caesar Shift you need to cast the result back to a (char)
when you print it, as in:
System.out.print ((char)(expression))
Otherwise you'll get the int
value of the expression.