Java Int & ASCII Questions

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));
}

      

Okay what I'm trying to do is take the WEDGEZ string and shift each letter by 5, so W becomes B and E becomes J, etc. However, I feel there is some inconsistency with the numbers I use, For the if statement I use ASCII values, and for the letterMix = statement I use numbers from 1-26 (I think). Actually the question about this too: What does (char) (('D' + (letter - 'D' + shift)% 26)); come back anyway? It returns the right char, but converts from int. I found this expression on the internet somewhere, I haven't compiled it completely myself, so what exactly does this statement return.

A common problem with this code is that for W it returns '/', and for Z it returns _, which I assume means its using ASCII values. I really don't 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));
            }
        }

      

+1


source to share


1 answer


Ok, I'm not sure if this is homework, so I'll be stingy with the code.

You write Caesar Cipher with a shift of 5.

To solve your problem Z

_

... I assume that you want all the letters have been replaced by coded letters (not strange symbols). The problem is that the ASCII values A-Z

are between 65 and 90. When encoding Z

(for example), you end up adding 5 to it, which gives the value 95 ( _

).

What you need to do is wrap the available alphabets. First highlight, the relative position of the character in the alphabets (ie A = 0, B = 1 ...) You need to subtract 65 (that's ASCII A

. Add yours Shift

and then apply modulus 26

. This will make your value wrap around.

for example this is your encoding Z

, (ASCII = 90), so the relative position is 25 (= 90 - 65). now 25 + 5 = 30, but you need the value to be within 26. so you take modulus 26

therefore 30 % 26

there is 4

which is E

.

So here



char letter = message(i);
int relativePosition = letter - 'A'; // 0-25
int encode = (relativePosition + shift) % 26
char encodedChar = encode + 'A' // convert it back to ASCII.

      

So in one line

char encodedChar = 'A' + (  ( (letter - 'A') + shift ) % 26)

      

Note. This will only work for uppercase letters, if you plan on using lowercase letters you will need additional processing.

You can use Character.isUpperCase()

to check uppercase.

+5


source







All Articles