String source = "WEDGEZ"
char letter = source.charAt(i);
shift=5;
for (int i=0;i<source.length();i++){
if (source.charAt(i) >=65 && source.charAt(i) <=90 )
letterMix =(char)(('D' + (letter - 'D' + shift) % 26));
}
Ok what I’m trying to do is take the string WEDGEZ, and shift each letter by 5, so W becomes B and E becomes J, etc. However I feel like there is some inconsistency with the numbers I’m using.
For the if statement, I’m using ASCII values, and for the
letterMix= statement, I’m using the numbers from 1-26 (I think). Well actually, the question is about that too:
What does
(char)(('D' + (letter - 'D' + shift) % 26)); return anyway? It returns a char right, but converted from an int. I found that statement online somewhere I didn’t compose it entirely myself so what exactly does that statement return.
The general problem with this code is that for W it returns ‘/’ and for Z it returns _, which I’m guessing means it’s using the ASCII values. I really dont know how to approach this.
Edit: New code
for (int i=0;i<source.length();i++)
{
char letter = source.charAt(i);
letterMix=source.charAt(i);
if (source.charAt(i) >=65 && source.charAt(i) <=90 ){
letterMix=(char)('A' + ( ( (letter - 'A') + input ) % 26));
}
}
Well I’m not sure if this homework, so i’ll be stingy with the Code.
You’re Writing a Caesar Cipher with a shift of 5.
To address your
Z->_problem…I’m Assuming you want all the letters to be changed into encoded letters (and not weird Symbols). The problem is ASCII values ofA-Zlie between 65 and 90.When coding
Z(for eg), you end up adding 5 to it, which gives u the value 95 (_).What you need to do is Wrap around the available alphabets. First isolate, the relative position of the character in the alphabets (ie A = 0, B = 1 …) You Need to subtract 65 (which is ASCII of
A. Add yourShiftand then applymodulus 26. This will cause your value to wrap around.eg, it your encoding
Z, (ASCII=90), so relative position is 25 (= 90 – 65).now, 25 + 5 = 30, but you need the value to be within 26. so you take
modulus 26so
30 % 26is4which isE.So here it is
So in one line,
Note, This will work only for upper case, if your planning to use lower case, you’ll need some extra processing.
You can use
Character.isUpperCase()to check for upper case.