Java 程序加密不正确

Java 程序加密不正确,java,Java,我正在开发一个接受用户输入的程序(一个输入txt文件,要移位的空格数,移位的方向,以及他们想要创建的output.txt文件的名称)。我的程序正在编译,当我运行它的时候,它会创建一个输出文件,但是结果并没有达到应有的水平。例如,如果我将其设置为使用3的移位进行加密,并且方向正确,则单词应该更改为WKH。目前,我还没有实现这个方向,因为我似乎不知道我将如何做到这一点,以转移到左边。有谁能看一下我的代码,帮我找到正确的方向?非常感谢您抽出时间 import java.util.*; import j

我正在开发一个接受用户输入的程序(一个输入txt文件,要移位的空格数,移位的方向,以及他们想要创建的output.txt文件的名称)。我的程序正在编译,当我运行它的时候,它会创建一个输出文件,但是结果并没有达到应有的水平。例如,如果我将其设置为使用3的移位进行加密,并且方向正确,则单词应该更改为WKH。目前,我还没有实现这个方向,因为我似乎不知道我将如何做到这一点,以转移到左边。有谁能看一下我的代码,帮我找到正确的方向?非常感谢您抽出时间

import java.util.*;
import java.io.*;

public class CaeserCipher {

  public static void main(String[] args)throws IOException {

        String originalText="";
        String inputFile;
        String outputFile = "";
        String shiftDirection;
        int shiftValue;
        Scanner keyboard = new Scanner(System.in);

        //Prompt user for input file name
       Scanner in = new Scanner(System.in);
       System.out.print("What is the filename?: ");
       inputFile = in.nextLine();


       //make sure file does not exist
            File file = new File(inputFile);
               if (!file.exists())
               {
                  System.out.println("\nFile " + inputFile + " does not exist. File could not be opened.");

                  System.exit(0);
               }

         //send the filename to be read into String

         originalText = readFile(inputFile);


         //Prompt user for shift value
         System.out.print("\nWhat is the shift value? ");
         shiftValue = keyboard.nextInt();

         //Prompt user for shift direction
         Scanner sc = new Scanner(System.in);
         System.out.print("What direction would you like to shift? Press L for left or R for right: ");

         //validate the input
         while (!sc.hasNext("[LR]")) {
             System.out.println("That's not a valid form of input! Please enter only the letter 'L' or 'R': ");
             sc.next();
             shiftDirection = sc.next(); //stores the validated direction
         }//end while

         shiftDirection = sc.next(); //stores the validated direction

         //Return encrypted string
         String encryptedText = encrypt(originalText , shiftValue);

         //get the outputfile name
         System.out.print("What is the name of the output file you want to create?: ");
         outputFile = in.nextLine();

         //make sure file does not exist
         File file2 = new File(outputFile);
            if (file2.exists())
            {
               System.out.println("\nFile " + outputFile + " already exists. Output not written.");

               System.exit(0);
            }

        try {
            File file3 = new File(outputFile);
            BufferedWriter output = new BufferedWriter(new FileWriter(file3));
            output.write(encryptedText);
            output.close();
        } catch ( IOException e ) {
            e.printStackTrace();
        }
        System.out.println("\nOutput written to " + outputFile);        

    } //end main

    //rotate and change chars
    public static String rotate(String userString, int shiftValue) {

        String convertedText = "";
        for(int i = 0; i < userString.length(); i++){
        char lowerLetter = userString.charAt(i);

        //Convert to uppercase
        char upperLetter = Character.toUpperCase(lowerLetter);
        int charNumber = upperLetter;

        //Apply shift, remembering to wrap text
        int rotateShift = (charNumber + shiftValue) % 26;
        char shiftLetter = (char) rotateShift;

        //Create new string of shifted chars
        convertedText += shiftLetter;
        }
      return convertedText;
    }

    //encrypt
    public static String encrypt(String userString, int shiftValue) {
        String encryptedString = rotate(userString , shiftValue);
        return encryptedString;
    }

    private static String readFile(String inputFile) throws java.io.IOException {
      File file = new File(inputFile);
      StringBuilder fileContents = new StringBuilder((int) file.length());
      Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));
      String lineSeparator = System.getProperty("line.separator");

         try {
             if (scanner.hasNextLine()) {
                 fileContents.append(scanner.nextLine());
             }
             while (scanner.hasNextLine()) {
                 fileContents.append(lineSeparator + scanner.nextLine());
             }

         return fileContents.toString();
    }


     finally {
        scanner.close();
    }

 }
}
import java.util.*;
导入java.io.*;
公共类CaeserCipher{
公共静态void main(字符串[]args)引发IOException{
字符串originalText=“”;
字符串输入文件;
字符串outputFile=“”;
字符串移位方向;
int移位值;
扫描仪键盘=新扫描仪(System.in);
//提示用户输入文件名
扫描仪输入=新扫描仪(系统输入);
System.out.print(“文件名是什么?:”);
inputFile=in.nextLine();
//确保文件不存在
文件文件=新文件(inputFile);
如果(!file.exists())
{
System.out.println(“\n文件“+inputFile+”不存在。无法打开文件。”);
系统出口(0);
}
//将要读取的文件名发送到字符串中
originalText=readFile(inputFile);
//提示用户输入移位值
System.out.print(“\n移位值是多少?”);
shiftValue=keyboard.nextInt();
//提示用户输入换档方向
扫描仪sc=新的扫描仪(System.in);
System.out.print(“您想改变什么方向?按L向左或按R向右:”);
//验证输入
而(!sc.hasNext(“[LR]”){
System.out.println(“这不是有效的输入形式!请只输入字母‘L’或‘R’:”;
sc.next();
shiftDirection=sc.next();//存储已验证的方向
}//结束时
shiftDirection=sc.next();//存储已验证的方向
//返回加密字符串
字符串encryptedText=encrypt(原始文本,移位值);
//获取输出文件名
System.out.print(“要创建的输出文件的名称是什么?:”;
outputFile=in.nextLine();
//确保文件不存在
文件file2=新文件(outputFile);
if(file2.exists())
{
System.out.println(“\n文件”+outputFile+”已存在。输出未写入。“);
系统出口(0);
}
试一试{
文件file3=新文件(outputFile);
BufferedWriter输出=新的BufferedWriter(新的FileWriter(file3));
输出.写入(加密文本);
output.close();
}捕获(IOE异常){
e、 printStackTrace();
}
System.out.println(“\n输出写入”+输出文件);
}//末端总管
//旋转和更换字符
公共静态字符串旋转(字符串userString,int-shiftValue){
字符串convertedText=“”;
对于(int i=0;i
您的问题是
%26
。你没有考虑角色是如何工作的。您需要这样做:

int rotateShift = ((charNumber - 'A' + shiftValue) % 26) + 'A';
您之前所做的是错误的,因为
char
是一个ASCII值。这意味着
'A'==65
,因此,要将字符表示形式转换为数字,应首先从字符值中细分
'A'
。这映射了
A->0,B->1,C->2,…
。然后,当您完成
Caesar Shift
时,您需要将
'A'
的值加回到整数,以将其转换回ASCII字符

Java的
%
操作符也可能会遇到另一个问题。Java的模块化操作符的操作如下:

-4 % 5 == -4
因此,我将编写一个加密mod函数:

public int crypto_mod(int num, int mod)
{
    num %= mod;
    if(num < 0) num += mod;
    return num;
}
public int-crypto_-mod(int-num,int-mod)
{
num%=mod;
如果(num<0)num+=mod;
返回num;
}

这将生成您要查找的字符。

确实如此!但是,它没有显示相同的内容(我使用了一个四行文本的输入文件,它显示为:`aahsgashashadhajshsjahsjahsajshaajshaj*jashajsha'。为什么它在两行之间加上星号而不是在单独的行上显示它们呢?谢谢