Answer:
See explaination
Explanation:
import java.util.Scanner;
public class EncodeDecodeMessage {
public static String encode(String str) {
String result = "";
char ch;
for(int i = 0; i < str.length(); ++i) {
ch = str.charAt(i);
if(Character.isLowerCase(ch)) {
result += (char)('a' + (25-ch+'a'));
} else if(Character.isUpperCase(ch)) {
result += (char)('A' + (25-ch+'A'));
} else {
result += ch;
}
}
return result;
}
public static String decode(String str) {
return encode(str); // since the scheme is same, we can use encode for decode
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("1. Encode, 2. Decode. Enter your choice: ");
int choice = in.nextInt();
in.nextLine();
if(choice == 1) {
System.out.print("Enter sentence to encode: ");
String line = in.nextLine();
System.out.println("Encoded string is: " + encode(line));
} else if(choice == 2) {
System.out.print("Enter sentence to decode: ");
String line = in.nextLine();
System.out.println("Decoded string is: " + decode(line));
}
}
}