Home > Net >  Encrypt a Paragraph of Text in Java
Encrypt a Paragraph of Text in Java

Time:02-16

I am trying to make a game where a paragraph of text is “encrypted” using a simple substitution cipher, so for example, all A's will be F's and B's will be G's an so on. The idea is that the user/player will need to try to guess the famous quote by trying to decrypt the letters. So the screen shows them a blank space with a letter A and they have to figure out it's really an F that goes in the place within the string. I've not got very far, basically I can manually change each letter using a for loop, but there must be an easier way.

import java.util.Scanner;
import java.util.Random;

public class cryptogram {
    

    public static void main(String[] args) {
        
        char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
        
        for (char i = 0; i <alphabet.length; i  ) {
            if (alphabet[i] == 'B') {
                    alphabet[i] = 'Z';
            }
        }
        System.out.println(alphabet);
    }
}

CodePudding user response:

Substitution

A "substitution" workflow might look something like...

public class Main {

    public static void main(String[] args) {
        new Main().substitution();
    }
    
    public void substitution() {
        char[] lookup = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".toCharArray();
        char[] substitution = " FGHIJKLMNOPQRSTUVWXYZABCDE".toCharArray();
        
        String text = "This is a test";
        StringBuilder builder = new StringBuilder(text.length());
        for (char value : text.toCharArray()) {
            int index = indexOf(value, lookup);
            builder.append(substitution[index]);
        }
        
        String encypted = builder.toString();
        
        System.out.println(text);
        System.out.println(encypted);

        builder = new StringBuilder(text.length());
        for (char value : encypted.toCharArray()) {
            int index = indexOf(value, substitution);
            builder.append(lookup[index]);
        }
        System.out.println(builder.toString());
    }
    
    protected static int indexOf(char value, char[] array) {
        char check = Character.toUpperCase(value);
        for (int index = 0; index < array.length; index  ) {
            if (check == array[index]) {
                return index;
            }
        }
        return -1;
    }
}

Which will output something like...

This is a test
XLMWEMWE EXIWX
THIS IS A TEST

Now, obviously, this only supports upper-cased characters and does not support other characters like numbers or punctuation (like ! for example). The above example will also crash if the character can't be encoded, it's just an example of an idea after all

  • Related