My task is:

The Captain Crunch decoder ring works by taking each letter in a string and adding 13 to it. For example, ’a’ becomes ’n’ and ’b’ becomes ’o’. The letters “wrap around” at the end, so ’z’ becomes ’m’.

Write a method that takes a String and that returns a new String containing the encoded version. You should assume that the String contains upper and lower case letters, and spaces, but no other punctuation. Lower case letters should be transformed into other lower case letters; upper into upper. You should not encode the spaces.

package junk;

public class Main {

    public static void main(String[] args) {
        
        String alphabet = "abcdefghijklmnopqrstuvwxyz";

        int index = 0;
        while (index < alphabet.length ()) {
            char letter = alphabet.charAt (index);
            System.out.println (letter);
            index = index + 1;
        }
    }

}

So far my program only gives me output of all of the alphabets in the string. How should I take a from the string and get n, take b and get o consecutively until I take z and get m. Please Help :(

You should look up the modulus operator ( which in java is % ) to solve this problem..

What you could do is take your input one letter at a time. Compare it in a loop to you alphabet. When a letter matches you increment your alphabet index by 13 and append that letter to your output variable. Be careful of index out of bounds exceptions which can be prevented with a nested if statement.

Now I have this:

package captaincrunch;

public class Main {

    public static void main(String[] args) {
        // TODO code application logic here
        String alphabet = "abcdefghijklmnopqrstuvwxyz";
        char letter;

        for (int index = 0, size = alphabet.length (); index < size; index++) {
            letter = alphabet.charAt ((index + 13) % size);
            System.out.println ("Original: " + alphabet.charAt (index) + ", Encoded: " + letter);
        }
    }

}

I need to generalize the method so that instead of adding 13 to the
letters, it adds any given amount.

Now I have this:

package captaincrunch;

public class Main {

    public static void main(String[] args) {
        // TODO code application logic here
        String alphabet = "abcdefghijklmnopqrstuvwxyz";
        char letter;

        for (int index = 0, size = alphabet.length (); index < size; index++) {
            letter = alphabet.charAt ((index + 13) % size);
            System.out.println ("Original: " + alphabet.charAt (index) + ", Encoded: " + letter);
        }
    }

}

I need to generalize the method so that instead of adding 13 to the
letters, it adds any given amount.

Then put the code in a method with one argument and replace the 13 with that argument.
Then call the method with whatever argument you want.

This article has been dead for over six months. Start a new discussion instead.