使用Java中的旋转数量和方向进行加密

时间:2015-04-22 21:10:12

标签: java

我有一个程序,我创建了一段时间,从用户获取一个字符串并加密它。我正在开发一个程序的第二个版本,它从用户那里获取一个文本文件,让用户输入一个移位值,让用户输入移位的方向(左或右),然后输出加密的消息给一个新文件。

由于其他成员的帮助,我现在正在使用该程序,但这不是我想要的方式。现在它接收文件并加密到文件,但不使用移位或方向。如果用户选择例如3的移位和右移,则程序应该读取文本文件的第一个字母并旋转键数组3个空格并打印字符。然后程序查看下一个字母,将数组向右旋转3个空格,然后打印该字符。我真的很困惑我将如何改变方向。我知道我需要发送加密方法,从文件创建的字符串,移位方向和移位量,然后使用循环来完成所有内容,但这比我的理解有点高。任何有关该过程的帮助将不胜感激!对于长代码很抱歉,但我希望您能够看到发生的所有事情。

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 - 'A' + shiftValue) % 26) + 'A';
        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();
    }

 }
}

这是我之前用于加密一个字符串的方法,该字符串没有用户输入的移位数量或方向:

public static String doEncryption(String s)
    {
        char alphabet[]  = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
            'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z' };   //hold the characters in alphabet array
        char key[] = { 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
            'x', 'y', 'z', 'a' };   //holds characters in the key array

        char encoded[] = new char[(s.length())];
        String encrypted="";  //initialize the string for the new message
        int j=0;     //count variable
        for(int i=0; i<s.length(); i++){  //begin for loop to run through string
            boolean isFound = false;
            j = 0;
            while (j < alphabet.length && !isFound){


                if (alphabet[j]==s.charAt(i)){
                   encrypted=encrypted+key[j];
                   isFound=true;
                }
                j++; 
            }
}

任何人都可以帮助我理解每次到达文件中的新字母时旋转数组需要做什么?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用ArrayList<String>代替char[]。将key[j]替换为key.get(j)。使用for循环旋转ArrayList并调用String s = key.remove(0)key.add(s)