我用java做了一个vigenere密码。加密工作正常,但我无法解密。这是我的代码
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Do you want to encrypt or decrypt? (E/D): ");
String mode = scanner.nextLine().toUpperCase();
System.out.print("Input file name: ");
String inputFileName = scanner.nextLine();
System.out.print("Output file name: ");
String outputFileName = scanner.nextLine();
System.out.print("Keyword (all capitals): ");
String keyword = scanner.nextLine().toUpperCase();
scanner.close();
try {
BufferedReader reader = new BufferedReader(new FileReader(inputFileName));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName));
int keywordIndex = 0;
String line = reader.readLine();
while (line != null) {
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (Character.isLetter(c)) {
int shift = keyword.charAt(keywordIndex) - 'A';
if (mode.equals("D")) {
shift = 26 - shift;
}
else {
c = (char)(((c + shift - 'A') % 26) + 'A');
keywordIndex = (keywordIndex + 1) % keyword.length();
c = Character.toUpperCase(c);
}
}
writer.write(c);
}
writer.newLine();
line = reader.readLine();
}
reader.close();
writer.close();
System.out.println("Done.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
除了解密部分,代码的所有部分都运行正常。由于某种原因,它无法解密。它也创建了我的输出文件,但加密是1相同的或2再次加密。
1条答案
按热度按时间igetnqfo1#
最里面的
else
块的内容应该高一级。你格式化代码的方式,这绝对是你的意图,但你的IDE只是添加了一个不必要的else{}
:-)只需注解掉两行,它应该工作: