Substitution Cipher Technique Solution

Substitution Cipher Technique Solution

Ava sitting in the first row wants to send a secret message to her friend Mia who is sitting in the last row. She wrote a secret message in a piece of paper and passed it through her classmates. Ava has used a substitution cipher technique where every letter is replaced with the 7th alphabet before the letter in the alphabet series. Since Mia already knows the technique she easily got the exact message.

The encrypted text (input) may have numbers or special characters along with letters. If so, ignore those and convert only the letters. If space occurs between the words of input, it must occur in output also. If no letters, then there is “No hidden message”.

Develop a java application that accepts the secret message to decrypt and print the actual message to the screen. Input consists of the encrypted text.

Sample Input 1

Enter the encrypted text:
Pukph

Sample Output 1 Decrypted text: India

Sample Input 2 Enter the encrypted text: Z23hcl @d$3#haly

Sample Output 2 Decrypted text: Save water

Sample Input 3 Enter the encrypted text: @67$89##^^

Sample Output 3 No hidden message

SOLUTION

Program: Substitution Cipher Technique Solution in Java

import java.util.*;

public class Main {
    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder();
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter the encrypted text:");
        String text = scanner.nextLine();
        char[] chars = text.toCharArray();
        boolean flag = false;

        for (char ch : chars) {
            if (Character.isLetter(ch)) {
                flag = true;

                if (Character.isLowerCase(ch)) {
                    int sub = (int) ch - 7;

                    if (sub < 97) {
                        ch = (char) (122 - (97 - sub) + 1);
                    } else {
                        ch = (char) sub;
                    }
                } else if (Character.isUpperCase(ch)) {
                    int sub = (int) ch - 7;

                    if (sub < 65) {
                        ch = (char) (90 - (65 - sub) + 1);
                    } else {
                        ch = (char) sub;
                    }
                }

                stringBuilder.append(ch);
            } else if (Character.isWhitespace(ch)) {
                stringBuilder.append(ch);
            }
        }

        if (flag) {
            System.out.println("Decrypted text:");
            System.out.println(stringBuilder.toString());
        } else {
            System.out.println("No hidden message");
        }
    }
}

Related:

Leave a Comment

four × five =