[英]Caesar Cipher not reading words after a space, cannot figure out why
I need to write a simple Caesar cipher for an assignment and I have to encrypt the message "This is a Caesar cipher" with a left shift of 3. I have tried using an IF statement followed by 'continue;' 我需要为一个赋值编写一个简单的Caesar密码,我必须加密消息“This is a Caesar cipher”,左移为3.我尝试使用IF语句后跟'continue;' but it is not working, I cannot for the life of me figure out what is causing this problem haha.
但它不起作用,我不能为我的生活找出导致这个问题的原因哈哈。
public static String encrypt(String plainText, int shiftKey) {
plainText = plainText.toLowerCase();
String cipherText = "";
for (int i = 0; i < plainText.length(); i++) {
char replaceVal = plainText.charAt(i);
int charPosition = ALPHABET.indexOf(replaceVal);
if(charPosition != -1) {
int keyVal = (shiftKey + charPosition) % 26;
replaceVal = ALPHABET.charAt(keyVal);
}
cipherText += replaceVal;
}
return cipherText;
}
public static void main (String[] args) {
String message;
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter a sentence to be encrypted");
message = new String();
message = sc.next();
}
System.out.println("The encrypted message is");
System.out.println(encrypt(message, 23));
}
} }
You are only reading one word with Scanner.next()
and never use new String()
. 您只使用
Scanner.next()
读取一个单词,并且从不使用new String()
。 Change 更改
message = new String();
message = sc.next();
to 至
message = sc.nextLine();
It's also worth noting that StringBuilder
and simple arithmetic is all you need for a Caesar Cipher. 值得注意的是,
StringBuilder
和简单算术就是Caesar Cipher所需要的。 For example, 例如,
public static String encrypt(String plainText, int shiftKey) {
StringBuilder sb = new StringBuilder(plainText);
for (int i = 0; i < sb.length(); i++) {
char ch = sb.charAt(i);
if (!Character.isWhitespace(ch)) {
sb.setCharAt(i, (char) (ch + shiftKey));
}
}
return sb.toString();
}
public static void main(String[] args) {
int key = 10;
String enc = encrypt("Secret Messages Are Fun!", key);
System.out.println(enc);
System.out.println(encrypt(enc, -key));
}
Which outputs 哪个输出
]om|o~ Wo}}kqo} K|o Px+
Secret Messages Are Fun!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.