Question

package edu.secretcode;

import java.util.Scanner;

/**
 * Creates the secret code class.
 * 
 * @author
 * 
 */
public class SecretCode {
    /**
     * Perform the ROT13 operation
     * 
     * @param plainText
     *            the text to encode
     * @return the rot13'd encoding of plainText
     */

    public static String rotate13(String plainText) {
        StringBuffer cryptText = new StringBuffer("");
        for (int i = 0; i < plainText.length() - 1; i++) {
            char currentChar = plainText.charAt(i);
            currentChar = (char) ((char) (currentChar - 'A' + 13) % 26 + 'A');
            cryptText.append(currentChar);
            if (currentChar <= 'A' || currentChar >= 'Z') {
                cryptText.append(plainText.charAt(i));
            }

            else {
                currentChar = (char) ((char) (currentChar - 'A' + 13) % 26 + 'A');
                cryptText.append(currentChar);
            }

        }
        return cryptText.toString();

    }

    /**
     * Main method of the SecretCode class
     * 
     * @param args
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (1 > 0) {
            System.out.println("Enter plain text to encode, or QUIT to end");
            Scanner keyboard = new Scanner(System.in);
            String plainText = keyboard.nextLine();
            if (plainText.equals("QUIT")) {
                break;
            }
            String cryptText = SecretCode.rotate13(plainText);
            String encodedText = SecretCode.rotate13(plainText);

            System.out.println("Encoded Text: " + encodedText);
        }

    }

}

Hello everyone, I am wanting this program to encode uppercase letters and leave the other characters alone and pass them through the output. For example "HELLO WORLD!" should become after running the program "URYY\ d_YQ!" and I am getting YLUHREYLYLBOWJJWBOERYLQDXK instead of "URYY\ d_YQ!" which is what I am suppose to get. If anyone can let me know what I did wrong I would greatly appreciate it. Thanks in advance.

Was it helpful?

Solution

It would be easier if you used String matching with regular expressions. First of all, in your loop condition, eliminate -1. Otherwise you're only getting to the second to last character.

Next, eliminate the cryptText.append(currentChar); before the if statement. Then, use this

char currentChar = plainText.charAt(i);
String cS = currentChar+"";
currentChar = (char) ((char) (currentChar - (int)'A' + 13) % 26 + (int)'A');

if (!cS.matches("[A-Z]")) {

    cryptText.append(plainText.charAt(i));
}
else {
    cryptText.append(currentChar);
}

This actually works, except that I'm getting some different characters from what you want. HELLO WORLD! => URYYB JBEYQ!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top