我在java中为caesar cipher编写了一个程序,程序将文本文件作为输入存储在我的计算机中,并根据用户提供的键值对其进行加密。然后,此加密文件必须以文本文件格式保存在计算机上。我一直试图找到我出错的地方,但我想我需要一些经验丰富的java帮助。所以继承我的代码:
import java.util.Scanner;
import java.io.*;
import java.lang.*;
public class trial
{
public static void main(String arg[])
{
String textFile="plaintext.txt";
String cipheredFile=" ciphertext.txt";
String line= null;
FileReader fileReader=new FileReader(textFile);
BufferedReader bufferedReader=new BufferedReader(fileReader);
FileWriter fileWriter= new FileWriter(cipheredFile,true);
BufferedWriter bufferedWriter= new BufferedWriter(fileWriter);
int swvalue;
Scanner input= new Scanner(System.in);
System.out.println("Select 1: Encrypt, 2: Decrypt, 3: Get Frequency");
int msg= input.nextInt();
swvalue= Integer.valueOf(msg);
switch(swvalue)
{
case 1:
System.out.println("Encrypting the file");
System.out.println(" Please enter a value for key");
int keyvalue= input.nextInt();
String[] filearray=null;
while(( line=bufferedReader.readLine())!=null)
{
char[] toEncrypt=line.toCharArray();
for(int i=0;i<toEncrypt.length;i++)
{
int charPosition= indexOf(line.charAt(i));
int finalValue=(keyValue+charPosition)%26;
char replaceValue=line.charAt(finalValue);
line+=replaceValue;
}
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
break;
case 2:
System.out.println("Decrypt the file");
break;
case 3:
System.out.println(" Get frequency");
break;
}
}
}
答案 0 :(得分:0)
这是旋转的位置:
int charPosition= indexOf(line.charAt(i)); int finalValue=(keyValue+charPosition)%26;
但这不是轮换!
不应在字符串中移动位置,而应将 值移至 :
int value = line.charAt(i);
int finalValue=(keyValue+value)%26;