CIS 3020 Project 5
Jump to navigation
Jump to search
Code
Cipher.java
import java.lang.String; public class Cipher { //output string that holds encrypted message private String output = new String(); //replacement letter for encryption (changes often!) private String replacement = new String(); //how to know when to stop trying to replace letters private int keyLen = 0; private void clearOutput(){ //clear this.output this.output = ""; } public String getOutput(){ //return output return(this.output); } public String encipher (String encode, String key, String message){ //reset this.output clearOutput(); //determine key length this.keyLen = (key.length()-1); //return the encoded message return(encode(encode, key, message)); } private String encode(String encode, String key, String message) { //is there anything left to encode? if (message.length() != 0) { // Get the first character in the initiator string. //the following two lines (3 lines if you really want to, //but letterReplacement would have to return this.replacement) //could have been combined but weren't for clarity. String letter = message.substring(0, 1); //replace letter with encrypted letter letterReplacement(letter, encode, key, 0); //concatenate output with encoded letter this.output = this.output.concat(this.replacement); //repeat for next letter encode(encode, key, message.substring(1)); } //end if //end big if (length != 0) return (this.output); }//end next generation private void letterReplacement(String letter, String encode, String key, int n){ //don't go out of bounds! if (n<=this.keyLen){ //try to replace letter with encoded character this.replacement = letter.replace(encode.charAt(n),key.charAt(n)); //did replacement succeed? if (this.replacement.equals(letter)){ //if not, try again letterReplacement(letter, encode, key, n+1); } } } }