This is the instruction: Develop code to encrypt a string given the following encryption key "DEFGHIJKLMNOPQRSTUVWXYZABC". The encryption key is positional, so that the letter A is replaced by D, B is replaced by E, etc. We will ignore case in our substitutions.
To implement Stage 1, you should write a static method named encrypt :
public static String encrypt(String text, String theKey)
This method takes in the string to encrypt (named text) and the key and returns the encrypted string.
If you are confused about how to proceed, then here are some steps you can take:
define a class constant outside the method :
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
Inside the method, create a new string which is a lower case version of the parameter "text". We will replace the lower case characters with upper case key characters from the key so as to avoid the problem of replacing a character twice.
Create a loop that considers each character of the key (loop 26 times). Inside the loop :
extract the ith character from the key using the string method charAt.
extract the ith character from ALPHABET
call the replace method of the lower case text, changing the ith character of the alphabet to the ith character of the key.
And this is what I have so far for the code
A Issa wrote:Thanks the return resolved the problem. And you are right I am returning an empty string. Am I missing an if...else statement??
No, you don't need an if statement.
Consider what you are encrypting and what the for loop does.
Latin Upper Case letters are a nice touch for Caesar cipher.
> run Caesarcipher
Sebolela skull wrote:Can you please make a step-by-step on how to encrypt and decrypt from a text file?