Program opened below. You can scroll through the algorithm, Java code and output.
Program 82
Keyword Cipher
Question
Accept a keyword and a message in upper-case letters. Remove repeated letters from the keyword, build a cipher alphabet beginning with the keyword followed by unused letters A–Z, and encrypt the message by substituting each plain letter with its cipher counterpart.
Algorithm
Step 1: Start.
Step 2: Declare the variables and data structures required for the task.
Step 3: Input keyword and message.
Step 4: Convert both to upper case and validate letters/spaces.
Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution.
Step 6: Build a unique keyword by retaining only the first occurrence of each letter.
Step 7: Append unused letters from A to Z to form the cipher alphabet.
Step 8: For each message character, preserve spaces; otherwise find its index in the plain alphabet.
Step 9: Replace it with the character at the same index in the cipher alphabet.
Step 10: Display the cipher alphabet and encrypted message.
Step 11: Stop.
Java program
Javaimport java.util.*;
class KeywordCipher {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = sc.nextLine().toUpperCase(Locale.ROOT);
String msg = sc.nextLine().toUpperCase(Locale.ROOT);
if (!key.matches("[A-Z]+") || !msg.matches("[A-Z ]+")) {
System.out.println("INVALID INPUT");
return;
}
StringBuilder cipher = new StringBuilder();
for (char c : key.toCharArray()) {
if (cipher.indexOf(String.valueOf(c)) < 0) {
cipher.append(c);
}
}
for (char c = 'A'; c <= 'Z'; c++) {
if (cipher.indexOf(String.valueOf(c)) < 0) {
cipher.append(c);
}
}
StringBuilder out = new StringBuilder();
for (char c : msg.toCharArray()) {
out.append(c == ' ' ? ' ' : cipher.charAt(c - 'A'));
}
System.out.println("CIPHER ALPHABET: " + cipher);
System.out.println("ENCRYPTED TEXT: " + out);
}
}Sample output
Input:
ZEBRA
HELLO WORLD
Output:
CIPHER ALPHABET: ZEBRACDFGHIJKLMNOPQSTUVWXY
ENCRYPTED TEXT: FIPPN VNQPE