Can't compare 2 strings if a letter in first string exists in second string - java

Viewed 49

However I had an assignment of programming in java related to a text i already have under (text). the function is supposed to as below

getEncryptedText(int shift)

return a string representation of ciphertext given that the text to be manipulated is the plaintext using Caesar Cipher.

The number of rotation is depend on the shift value; positive shift value represent the right rotation while negative shift value represent left rotation. However, unlike explain in Wikipedia, this method used following string as plain: 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

Other characters than above will be treated as it is (i.e. will not been encrypted)

*Further reading: https://en.wikipedia.org/wiki/Caesar_cipher


So this is the class method I have made so far and wanted to know how can i keep the text chars which aren't included in the plaintext i have such as "!,@,#,$,%... and so on". So far i tried everything but couldn't make it but the rest seems fine!

public String getEncryptedText(int shift) {
  
    String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    String cipherText = "";
    for (int i = 0; i < text.length(); i++){
    {
        int charPosition = ALPHABET.indexOf(text.charAt(i));
        
        if(text.charAt(i) == ' ') {
            
            cipherText += " ";
        
        }
        
        else
        {      
        int keyVal = (shift + charPosition) % 62;
        
        char replaceVal = ALPHABET.charAt(keyVal);
        cipherText += replaceVal;
        }
    }
    }
    return cipherText;
}
1 Answers

Consider modifying your if statement and using the StringBuilder class:

class Main {
    public static void main(String[] args) {
        CesarCypherHelper cesarCypherHelper = new CesarCypherHelper();
        System.out.println(cesarCypherHelper.getEncryptedText("Hello World!", 2));
        System.out.println(cesarCypherHelper.getEncryptedText("Hello World!", 64));
    }
}

class CesarCypherHelper {
    public String getEncryptedText(String text, int shift) {
        String ALPHABET =
                "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        StringBuilder encryptedText = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
            int charPosition = ALPHABET.indexOf(ch);
            if (charPosition == -1) {
                encryptedText.append(ch);
            } else {
                int keyVal = (shift + charPosition) % ALPHABET.length();
                encryptedText.append(ALPHABET.charAt(keyVal));
            }
        }
        return encryptedText.toString();
    }
}

Output:

Jgnnq Yqtnf!
Jgnnq Yqtnf!
Related