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!”并且程序编码不正确。任何帮助,将不胜感激。提前谢谢。
答案 0 :(得分:1)
你将一个int而不是一个char附加到cryptText。使用:
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));