0

It doesn't replace the char with the one I want to and I cannot figure it out.

public static String encrypt(String message, int offset){
    String encrypted = message.toUpperCase();
    String aplhabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (int change = 0;change < encrypted.length();change++){
        for (int check = 0;check < aplhabet.length();check++){
            if (encrypted.charAt(change) == aplhabet.charAt(check)){
                offset = (check+offset)%27;
                encrypted.replace(encrypted.charAt(change),aplhabet.charAt(offset));
            }
        }
    }
    return encrypted;
}
  • 1
    String objects are immutable, but String *variables* can be changed, can reference a *new* String. So change `encrypted.replace(encrypted.charAt(change),aplhabet.charAt(offset));` to `encrypted = encrypted.replace(encrypted.charAt(change),aplhabet.charAt(offset));` – DontKnowMuchBut Getting Better Nov 08 '21 at 03:15
  • 1
    If you're going to do this, its best to convert the String to a char[], operate on the character array, and then reconvert to String. Not only will that let you work on mutable data, but it will cause far fewer string objects to be created and thus be more efficient. Also, you misspelled alphabet. – Gabe Sechan Nov 08 '21 at 03:18
  • 1
    @GabeSechan: or use a StringBuilder object. – DontKnowMuchBut Getting Better Nov 08 '21 at 03:28

0 Answers0