13.0k views
5 votes
This project involves writing a program that encodes and decodes messages. The program should prompt the user to select whether a message is to be encoded or decoded, and then prompts the user to enter the message. A blank space is used to separate each word in the message, and a period (.) is used to denote the end of a sentence. Separate methods must be used to encode and decode the input message. The coding scheme is very simple: the code

1 Answer

6 votes

Answer:

See explaination

Step-by-step 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));

}

}

}

User Christian Payne
by
4.5k points