0
package edu.secretcode;

import java.util.Scanner;

/**
 * Creates the secret code class.
 * 
 * 
 * 
 */
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++) {
            int currentChar = plainText.charAt(i);
            String cS = currentChar+"";
            currentChar = (char) ((char) (currentChar - (int) 'A' + 13) % 255 + (int)'A');
            if ((currentChar >= 'A') && (currentChar <= 'Z')) {
                currentChar = (((currentChar - 'A')+13) % 26) + 'A' - 1;
            }
            else {
                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);
        }

    }

}

如果结果字符大于“Z”,我需要通过向字符添加-13 来使这种旋转工作我想减去“Z”然后添加“A”然后减去 1(数字 1,而不是字母1') 并且仅对大写字母执行此操作。我在 if 语句和输入“HELLO WORLD!”时这样做了。我得到了 303923011009295302,我想得到“URYYB JBEYQ!” 并且程序没有正确编码。任何帮助,将不胜感激。提前致谢。

4

1 回答 1

1

You're appending an int rather than a char to cryptText. Use:

cryptText.append ((char)currentChar);

Update:

Wouldn't bother with the character value manipulation stuff. You're making all sorts of character set assumptions as it is (try running on an IBM i, which uses EBCDIC rather than ASCII, and watch it all break).

Use a lookup table instead:

private static final String in = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String out = "NOPQRSTUVWXYZABCDEFGHIJKLM";
...
final int idx = in.indexOf (ch);
cryptText.append ((-1 == idx) ? ch : out.charAt (idx));
于 2014-03-12T01:09:56.103 回答