Skip to content

Commit

Permalink
Update Vigenere.java
Browse files Browse the repository at this point in the history
- Remove continue;
- Change condition with Character.isLetter() and Character.isUpperCase();
  • Loading branch information
straiffix authored Apr 15, 2018
1 parent e48a9ad commit e53ec53
Showing 1 changed file with 25 additions and 21 deletions.
46 changes: 25 additions & 21 deletions ciphers/Vigenere.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,49 +8,53 @@

public class Vigenere {

public static String encrypt(final String message, final String key)
public static String encrypt(final String message, final String key)
{

String result = "";

for (int i = 0, j = 0; i < message.length(); i++)
{
for (int i = 0, j = 0; i < message.length(); i++) {
char c = message.charAt(i);
if (c >= 'A' && c <= 'Z') {
result += (char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A');
j = ++j % key.length();
} else if (c >= 'a' && c <= 'z') {
result += (char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a');
j = ++j % key.length();
if (Character.isLetter(c)){
if(Character.isUpperCase(c)) {
result += (char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A');

} else {
result += (char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a');

}
} else {
result+=c;
continue;
}
j = ++j % key.length();
}
return result;
}

public static String decrypt( final String message, final String key)
public static String decrypt( final String message, final String key)
{
String result ="";

for(int i = 0, j = 0; i < message.length(); i++){

char c = message.charAt(i);
if((c >= 'A' && c <= 'Z')){
result += ((char)('Z'-(25-(c-key.toUpperCase().charAt(j)))%26));
}
else if(c >= 'a' && c <= 'z'){
result += ((char)('z'-(25-(c-key.toLowerCase().charAt(j)))%26));
}
else{
if (Character.isLetter(c)){
if(Character.isUpperCase(c)) {
result += ((char)('Z'-(25-(c-key.toUpperCase().charAt(j)))%26));

} else {
result += ((char)('z'-(25-(c-key.toLowerCase().charAt(j)))%26));

}
} else {
result+=c;
continue;
}

j = ++j % key.length();

}
return result;
}
}
public static void main (String [] args){
String text="Hello World!";
String key="itsakey";
Expand All @@ -60,4 +64,4 @@ public static void main (String [] args){
System.out.println(decrypt(ciphertext, key));

}
}
}

0 comments on commit e53ec53

Please sign in to comment.