CalebN99
CalebN99

Reputation: 99

Caesar Cipher after the first space in a given String starts adding a char ( 'C' ) to the beginning of every word after that space

My Caesar cipher is adding a C at the beginning of every word after the first word in the message I want to rot. So I'm not sure if maybe it has to do with how I'm handling the spaces in the given message?

Expected output:

Your message? Attack zerg at dawn Encoding key? 3 DWWDFN CHUJ DW GDZQ

Current output:

Your message? Attack zerg at dawn Encoding key? 3 DWWDFN CCHUJ CDW CGDZQ

   public static void rot() {
        
       char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l',
               'm','n','o','p','q','r','s','t','u','v','w','x','y','z'};

        String rotM = "";

        Scanner scnr = new Scanner(System.in);
        System.out.print("Your message? ");
        String message = scnr.nextLine();
        System.out.print("Encoding key? ");
        int key = scnr.nextInt();

       message = message.toLowerCase();

        for (int i = 0; i < message.length(); i++) {
            if (!Character.isLetter(message.charAt(i))) rotM += " ";
            int origNumIndex = new String(alphabet).indexOf(message.charAt(i));
            int newIndex = origNumIndex + key;
            if (newIndex > 25) newIndex = newIndex - 26;
            char newLetter = alphabet[newIndex];
            rotM += newLetter;
        }

        System.out.println(rotM.toUpperCase());
        
   }

Upvotes: 0

Views: 130

Answers (1)

sb27
sb27

Reputation: 392

You forget a continue-statement. Without this continue, it tries to encode an unknown index. I added a failsafe, fixed and improved your code a bit:

public static void rot() {
    char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
            'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    String alphabetString = new String(alphabet);

    StringBuilder rotM = new StringBuilder();

    Scanner scnr = new Scanner(System.in);
    System.out.print("Your message? ");
    String message = scnr.nextLine();
    System.out.print("Encoding key? ");
    int key = scnr.nextInt();

    message = message.toLowerCase();

    for (int i = 0; i < message.length(); i++) {
        char ch = message.charAt(i);

        if (!Character.isLetter(ch)) {
            rotM.append(" ");
            continue; // <- This statement was missing
        }

        int index = alphabetString.indexOf(ch);

        if (index == -1)
            throw new IllegalStateException("Illegal character '" + ch + "'");

        rotM.append(alphabet[(index + key) % alphabet.length]);
    }

    System.out.println(rotM.toString().toUpperCase());

}

Upvotes: 1

Related Questions