My decipher program is not working correctly…
public static void decipherMessage() {
Scanner sc = new Scanner(in);
System.out.println("Enter keyword: ");
String decipher = sc.nextLine();
String plain = ("abcdefghijklmnopqrstuvwxyz");
String cipher = decipher + "abcdefghijklmnopqrstuvwxyz";
System.out.println("Enter enciphered message: ");
String ciphMsg = sc.nextLine();
String decipherMessage = ciphMsg.toLowerCase();
char[] chars = cipher.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
charSet.add(c);
}
StringBuilder cMap = new StringBuilder();
for (Character character : charSet) {
cMap.append(character);
StringBuilder original = cMap;
}
for (int i = 0; i < 26; i++)
{
char cipherTextChar = cMap.charAt(i);
char plainTextChar = plain.charAt(i);
decipherMessage = decipherMessage.replace(cipherTextChar,plainTextChar);
System.out.println("Deciphered message");
System.out.println(decipherMessage);
}
plain text letters are supposed to replace ciphered letters
but when I run it, it just gives the ciphered message again without deciphering?
example.
keyword: stack
plain : abcdefghijklmnopqrstuvwxyz
cipher: stackbdefghijlmnopqruvwxyz
message: overflow
ciphered message: mvhpbimw
except in reverse.
using the code I showed above it just gives the ciphered message again without deciphering anything.
Your code does replace characters, just not correctly (assuming that the usage of
deciphMsganddecipherMessageabove is a typo. They should be the same variable.)Well one problem is that you’re doing string replacement one cypher character at a time.
For example, if my cypher is “b”, it is supposed to switch all the a’s and the b’s, but if I give it the string
first it will replace all the a’s by b’s giving
and then replace all the b’s by a’s:
which is not the intended outcome.
The solution basically boils down to doing the replacement one message character at a time. You’ll have to loop over the message for that. You could also use a map to make it efficient.