【发布时间】:2017-08-16 13:07:49
【问题描述】:
我正在创建一个程序来执行 Caesar Cipher,当我按下回车键时,它会移动一个单词中的字母,并提示用户再次移动或退出。
在我达到 23 班 之前它一直有效,然后由于某种原因它开始使用非字母符号,我不确定为什么会发生这种情况。
有什么建议吗?代码如下:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Cipher {
public static void main(String[] args) {
// encrypted text
String ciphertext;
// input from keyboard
Scanner keyboard = new Scanner(System.in);
if (args.length > 0) {
ciphertext = "";
try {
Scanner inputFile = new Scanner(new File(args[0]));
while (inputFile.hasNext())
ciphertext += inputFile.nextLine();
} catch (IOException ioe) {
System.out.println("File not found: " + args[0]);
System.exit(-1);
}
} else {
System.out.print("Please enter text--> ");
ciphertext = keyboard.nextLine();
}
// -----------------------------------------------------------------
int distance = 0; // how far the ciphertext should be shifted
String next = ""; // user input after viewing
while (!next.equals("quit")) {
String plaintext = "";
distance += 1;
for (int i = 0; i < ciphertext.length(); i++) {
char shift = ciphertext.charAt(i);
if (Character.isLetter(shift)) {
shift = (char) (ciphertext.charAt(i) - distance);
if (Character.isUpperCase(ciphertext.charAt(i))) {
if (shift > '0' && shift < 'A') {
shift = (char) (shift + 26);
plaintext += shift;
} else {
plaintext += shift;
}
}
if (Character.isLowerCase(ciphertext.charAt(i))) {
if (shift > '0' && shift < 'a' && ciphertext.charAt(i) < 't') {
shift = (char) (shift + 26);
plaintext += shift;
} else {
plaintext += shift;
}
}
} else {
plaintext += shift;
}
}
System.out.println(ciphertext);
// At this point, plaintext is the shifted ciphertext.
System.out.println("distance " + distance);
System.out.println(plaintext);
System.out.println("Press enter to see the next option,"
+ "type 'quit' to quit.");
next = keyboard.nextLine().trim();
}
System.out.println("Final shift distance was " + distance + " places");
}
}
【问题讨论】:
-
你调试过你的代码吗?
-
...plaintext += shift; } else { plaintext += shift; }— 这没有意义。您可以将plaintext += shift语句放在else之外。 -
只是让您知道 - 过去的
'Z'和'z'是少数与字母无关的字符。你会想跳过那些。 -
@Isaiah 如果用户回答了您的问题,请同时接受他的回答 (Accepting Answers: How does it work?)。如果不是,请说明什么仍未得到答复,这是 StackOverflow 的一个非常重要的部分,非常感谢。
标签: java caesar-cipher