user2982832
user2982832

Reputation: 177

wrap around characters in characters

I have noticed a slight glitch in my program. It will decrypt every character except for a/b and c ( d is not included ). This is because it's a shift of -4. So obviously they're the only characters of the alphabet which loop round.... I've noticed y = 121 '-' = 95 ( 121-95=26 ) and w = 119 ']' = 93 ( 119-93=26 ) and 'x' = 120 and '^' = 94 (120-94=126).

if (p.isLetter(element))
{
    p = (char) (element + 5);
}
if(element > 'z' && Character.isLetter(element))
{
    element = (char)(element - 26);
}
else if(Character.isLetter(element))
{    element = (char)(element+ 26);
} 

Upvotes: 0

Views: 1228

Answers (1)

samgak
samgak

Reputation: 24427

The problem is that if you shift the character outside the range of a to z then isLetter() is going to return false so your two tests after applying the shift won't be met because the character is no longer a letter.

Put the isLetter() test around the whole block like this and remove it from the other ifs:

if (Character.isLetter(character))
{
    character = (char) (character + shift);
    if(character > 'z')
    {
        character = (char)(character - 26);
    }
    else if(character < 'a')
    {
        character = (char)(character + 26);
    }
}

The function only handles lowercase letters, so it would be more robust to change the check from isLetter() to:

if((character >= 'a') && (character <= 'z'))

Uppercase letters could be handled separately if needed.

Upvotes: 1

Related Questions