我正在努力转换我在网上找到的凯撒班次代码,以满足我的需求,添加不同的功能等等。
我想要求的唯一帮助是让代码直接从用户通过控制台工作,而不是通过Scanner
而不是InputStream
打开文件。我尝试自己修改代码,但到目前为止我唯一的运气是编译和输出:
Usage: java Caesar (-d | -e) key
但它不会让用户输入任何内容。我在下面发布了原始代码。任何建议或提示将不胜感激。 import java.io。*;
public class ShiftCipher {
private Reader in; // standard input stream for message
private int key; // (en|de)cryption key
// Caesar: constructor, opens standard input, passes key
public ShiftCipher(int k) {
// open file
in = new InputStreamReader(System.in);
key = k;
}
// (en|de)crypt: just feed in opposite parameters
public void encrypt() {
translate(key);
}
public void decrypt() {
translate(-key);
}
// translate: input message, translate
private void translate(int k) {
char c;
while ((byte) (c = getNextChar()) != -1) {
if (Character.isLowerCase(c)) {
c = rotate(c, k);
}
System.out.print(c);
}
}
// getNextChar: fetches next char.
public char getNextChar() {
char ch = ' '; // = ’ ’ to keep compiler happy
try {
ch = (char) in.read();
} catch (IOException e) {
System.out.println("Exception reading character");
}
return ch;
}
// rotate: translate using rotation, version with table lookup
public char rotate(char c, int key) { // c must be lowercase
String s = "abcdefghijklmnopqrstuvwxyz";
int i = 0;
while (i < 26) {
// extra +26 below because key might be negative
if (c == s.charAt(i))
return s.charAt((i + key + 26) % 26);
i++;
}
return c;
}
// main: check command, (en|de)crypt, feed in key value
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java Caesar (-d | -e) key");
System.exit(1);
}
ShiftCipher cipher = new ShiftCipher(Integer.parseInt(args[1]));
if (args[0].equals("-e"))
cipher.encrypt();
else if (args[0].equals("-d")) {
cipher.decrypt();
} else {
System.out.println("Usage: java Caesar (-d | -e) key");
System.exit(1);
}
}
}