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!",程序编码不正确。任何帮助都会很感激。
您正在向cryptText添加int而不是char。用途:
cryptText.append ((char)currentChar);
更新:不会为字符值操作而烦恼。您做出了各种各样的字符集假设(尝试在IBM i上运行,它使用EBCDIC而不是ASCII,并看着它全部崩溃)。
使用查找表代替:
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));