In: Computer Science
Create an interface MessageEncoder that has a single abstract method encode(plainText) where the plainText is the message to be encoded. The method will return the encoded version of the message. Then create a class SubstitutionCipher that implements this interface. The constructor should have on 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. Create a private method that shifts one character to help with this. Write a demo program that will take a message from a user , a shift value, and then return the encoded message.
use java
1. Interface
public interface MessageEncoder {
public StringBuilder encode(String plainText);
}
2. SubstitutionCipher Class
public class SubstitutionCipher implements MessageEncoder {
int shift;
public SubstitutionCipher(int shift) {
this.shift = shift;
}
@Override //overridding the encode interface method
public StringBuilder encode(String plainText) {
StringBuilder cipherText=new StringBuilder();
for (int i=0; i<plainText.length(); i++) {
cipherText.append(shifter(plainText.charAt(i)));
}
return cipherText;
}
private char shifter(char letter) {
char cipherAlpha;
if (Character.isUpperCase(letter)) // If plaintext charcter is Uppercase
cipherAlpha = (char)((((int)letter + shift - 65) % 26) + 65); // To restrictcharcters to english alphabets only
else // If plaintext character is Lowercase
cipherAlpha = (char)((((int)letter + shift - 97) % 26) + 97); // To restrict characters to english alphabets only
return cipherAlpha;
}
}
3. Demo Class
import java.util.*;
public class EncoderDemo {
public static void main(String[] args) {
int shift;
Scanner s = new Scanner(System.in);
System.out.println("Enter the shift Value");
shift= s.nextInt();
System.out.println("Enter the Plaintext you want to Encode");
String plainText;
plainText = s.next();
SubstitutionCipher aCipher = new SubstitutionCipher(shift);
StringBuilder CipherText= aCipher.encode(plainText);
System.out.println("Encoded plaintex is: "+CipherText);
}
}
Screenshot