Teacher’s Notes:
=======================================
You will need to copy the code key below into a file called key.txt and make this available to the students to do this assignment.
Assignment:
=======================================
Magic Spell Decoder
Merlin is a wizard who has decided to use a simple cypher to prevent his rivals from stealing his spells. To do this, he has replaced each letter of the alphabet with another letter. Each letter is only replaced with one other letter and once a letter is substituted, it cannot be used as a substitute for another letter. For example, if he substitutes 'a' with 'z', then 'a' cannot be substituted with any other letter. Also, 'z' could not be used as a substitute for any other letter.
You have come into possession of Merlin's cypher key. Write a program that will open the file "key.txt". This file is provided in the project folder. This file stores the replacement values for each letter in the alphabet in alphabetical order. The first letter in the file is the replacement for 'a', the second letter is the replacement for 'b', etc.
This program will then prompt the user to enter the coded spell name as a String from the keyboard. This input will always be made from only lower case letters and spaces. The program will not convert spaces but will include them in the same position in the decoded text.
The program will then use the key to decode the message to its original form. Once this is done, the program will print the decoded spell to the screen. Keep in mind that this String might have multiple words in it separated by spaces.
Sample Input 1:
hlulknyi uymnid xyyi
Sample Output 1:
vacation coming soon
Solution (JAVA):
=======================================
package code;
import java.io.File;
import java.util.Scanner;
public class Decoder {
public static char translate(char ch, char[] key) {
for(int x = 97; x < 123; x++)
if(key[x] == ch)
return (char)x;
return 32;
}
public static void main(String[] args)throws Exception {
char[] key = new char[123];
Scanner input = new Scanner(new File("key.txt"));
for(int x = 97; x < 123; x++)
key[x] = input.next().charAt(0);
Scanner message = new Scanner(new File("message.txt"));
String st = message.nextLine();
System.out.println(st);
String decodedMessage = "";
for(int x=0; x < st.length(); x++){
decodedMessage += translate(st.charAt(x),key);
}
System.out.println(decodedMessage);
}
}
Data For key.txt:
=======================================
l
c
u
e
a
w
d
r
n
g
b
p
m
i
y
f
s
z
x
k
j
h
v
t
o
q