90.3k views
3 votes
Create an interface MessageEncoder that has a single abstract method encode(plainText), where plainText is the message to be encoded. The method will return the encoded message.

Create a class SubstitutionCipher that implements the interface MessageEncoder, as described in the previous exercise. The constructor should have one parameter called shift. Define the method encode so that each letter is shifted by the value in shift. For example, if shift is 3, a will be replaced by d, b will be replaced by e, c will be replaced by f, and so on. Hint: You may wish to define a private method that shifts a single character.

All of this in Java

User Nafeeza
by
7.5k points

1 Answer

1 vote

Below is an example of the MessageEncoder interface and the SubstitutionCipher class in Java.

// MessageEncoder.java

public interface MessageEncoder {

String encode(String plainText);

}

// SubstitutionCipher.java

public class SubstitutionCipher implements MessageEncoder {

private int shift;

// Constructor

public SubstitutionCipher(int shift) {

this.shift = shift;

}

// Implementation of the encode method

Override

public String encode(String plainText) {

StringBuilder encodedText = new StringBuilder();

for (int i = 0; i < plainText.length(); i++) {

char originalChar = plainText.charAt(i);

User Whitebear
by
7.8k points