I'm stuck in my homework which is about a caesar cipher java program which includes an infinite while loop, char array, and a switch statement
I have to encode and decode messages
public class Main
{
public static int checkCharacter(char ch) {
if (Character.isUpperCase(ch)) {
return 1;
} else if (Character.isLowerCase(ch)) {
return 2;
} else {
return 3;
}
}
public static String encrypt(char chars[], int s)
{
StringBuffer result = new StringBuffer();
char ch;
int i = 0;
while(true)
{
if (i >= chars.length) {
break;
}
switch(checkCharacter(chars[i])) {
case 1:
ch = (char)(((int)chars[i] + s - 65) % 26 + 65);
result.append(ch);
break;
case 2:
ch = (char)(((int)chars[i] + s - 97) % 26 + 97);
result.append(ch);
break;
default:
break;
}
i ++;
}
return result.toString();
}
public static String decrypt(char chars[], int s)
{
StringBuffer result = new StringBuffer();
char ch;
int i = 0;
while(true)
{
if (i >= chars.length) {
break;
}
switch(checkCharacter(chars[i])) {
case 1:
ch = (char)(((int)chars[i] - s + 65) % 26 + 65);
result.append(ch);
break;
case 2:
ch = (char)(((int)chars[i] - s + 97) % 26 + 97);
result.append(ch);
break;
default:
break;
}
i ++;
}
return result.toString();
}
public static void main(String[] args)
{
String text = "ATTACKATONCE";
int s = 4;
System.out.println("Text : " + text);
String encrypted = encrypt(text.toCharArray(), s);
String decrypted = decrypt(encrypted.toCharArray(), s);
System.out.println("Encrypted text: " + encrypted);
System.out.println("Decrypted text: " + decrypted);
}
}
Get Answers For Free
Most questions answered within 1 hours.