2015-04-17 5 views
2

Я работаю над программой, которая принимает пользовательский ввод (входной файл 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(); 
    } 

} 
} 

ответ

4

Ваша проблема %26. Вы не рассматриваете, как работают ASCII символов. Вы должны сделать это вместо того, чтобы:

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 

Поэтому я хотел бы написать криптографическую функцию мод:

public int crypto_mod(int num, int mod) 
{ 
    num %= mod; 
    if(num < 0) num += mod; 
    return num; 
} 

Это должно произвести символы, которые вы ищете.

+0

Он делает! Однако вместо отображения того же (я использовал входной файл с текстом в четырех строках, он отображал его как «aahsgashashadh * ajshsjahsjahs * ajshaajshaj * jashajsha». Почему он помещал звездочку между строками, а не отображал их все на Отдельные строки? Спасибо за вашу помощь и сломаем, что это значит! – still2blue

+0

@ still2blue Ну, символ '' * ''меньше значения' 'A'', что заставляет меня думать, что вы не используете crypto_mod(). Попробуйте использовать crypto_mod() вместо обычной функции mod, и она должна работать отлично. – John