-6

I am trying to convert a letter to another letter in Java with a simple encryption program that would convert every letter for one place down the alphabetical scale, with the exception of the letter A (the value of A would be: "(0-1)"). So letter B would turn into A, letter C would turn into B, letter R would turn into Q and so on.

Example: I love fish would become H knud ehrg

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

1 Answers1

1

You could use something like the following algorithm to accomplish this:

// Our input string.
String input = "I love fish";

// Contains the "encrypted" output string.
StringBuilder encrypted = new StringBuilder();

// Process each character in the input string.
for (char c : input.toCharArray()) {
    if (Character.toLowerCase(c) != 'a' && Character.isLetter(c)) {
        // If the character is a letter that's not 'a', convert it to the previous letter.
        char previous = (char) ((int) c - 1);
        encrypted.append(previous);
    } else {
        // Otherwise just append the original character.
        encrypted.append(c);
    }
}

// Prints the output to stdout.
System.out.println(encrypted.toString());
ck1
  • 5,243
  • 1
  • 21
  • 25