我正在尝试在 java 中编写一个程序,该程序将像 vigenere 密码一样对字符串进行编码。一个示例运行将是
java Encrypt -e lemon < in.txt > out.txt
in.txt 应为 ATTACKATDAWN,out.txt 应为 LXFOPVEFRNHR,如果使用的参数数量不足,则应打印使用说明;但是,当我对此运行加密方法时,它会返回“??¡????¡??£?”,如果我对此运行解密方法,它会返回“?? ?????? ??? ?”,如果我输入的参数少于所需的两个参数,它会返回
线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1 在 Encrypt.main(Encrypt.java:22)
这是我的代码
import java.util.Scanner;
public class Encrypt
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
String msg = scan.nextLine();
String key = args[1];
if (args.length < 2)
{
System.out.println("Encryption program by ----");
System.out.println("Usage: java Encrypt [-e, -d] < inputFile > outputFile");
System.exit(0);
}
else if (args[0].equals ("-e"))
{
String emsg = encrypt(args[1], msg);
System.out.println(emsg);
}
else if (args[0].equals ("-d"))
{
String dmsg = decrypt(args[1], msg);
System.out.println(dmsg);
}
}
public static void usage(String[] args)
{
if (args.length < 2)
{
System.out.println("Encryption program by --------");
System.out.println("Usage: java Encrypt [-e, -d] < inputFile > outputFile");
System.exit(0);
}
}
public static String encrypt(String key, String msg)
{
String emsg = "";
for (int i = 0; i < msg.length(); i++)
{
int m = msg.charAt(i);
int k = key.charAt(i % key.length());
int e = (m + (k - 32));
char s = (char) e;
if (e > 126)
e = (e - (127 - 32));
emsg += s;
}
return emsg;
}
public static String decrypt(String key, String msg)
{
String dmsg = "";
for (int i = 0; i < msg.length(); i++)
{
int m = msg.charAt(i);
int k = key.charAt(i%key.length());
int e = (m - (k - 32));
char s = (char) e;
if (e > 126)
e = (e - (127 - 32));
dmsg += s;
}
return dmsg;
}
}
老实说,我不知道自己做错了什么;非常欢迎任何帮助!