2011-02-02 104 views
0

我一直在空閒時間寫這個加密算法幾天,我以爲我終於有了它的工作,但是當我對某些字符進行處理時,它開始出現故障。我已經設置了用輪換鍵來替換字符。問題在於,在翻譯完一個字符後就會被切斷。 解密代碼如下:解密程序中的奇怪錯誤

import java.util.Scanner; 
import java.io.*; 
/* File CycleDeCipher.java*/ 

public class CycleDeCipher 
{ 
    public static void main(String[] args) 
    { 
      new CycleDeCipher(); 
    } 
    public CycleDeCipher() 
    { 
      String plainTxt; 
      Scanner in = new Scanner(System.in); 
      System.out.println("This program decrypts My Cyclical Substitution Algorithm. v0.2"); 
      System.out.println("Enter a multi digit number : "); 
      Long mainKey = new Long(in.nextLong());; 
      System.out.print("Enter your Cipher Text message :"); 
      in.nextLine(); 
      plainTxt = new String(in.next()); 
      in.nextLine(); 
      int[] keys = longParser(mainKey); 
      String cipherTxt=""; 
      int j = 0; 
      while(j < plainTxt.length()) 
      { 
        cipherTxt+=decryptCharacter(plainTxt.charAt(j),keys[j%4]); 
        j++; 
        System.out.println("char number " + j + " successfully translated!"); 
      } 
      System.out.println("Your text is translated to :"+cipherTxt.toUpperCase()); 
    } 
    private String decryptCharacter(Character ch, int key) 
    { 
     System.out.println("Decrypting character "+ch.toString() + " with key "+key); 
     if(Character.isLetter(ch)){ 
      ch = (char) ((int) Character.toLowerCase(ch) - key%10); 
     } 
     else { 
      ch = (char) ((int) ch-key%10); 
     } 
     return(ch.toString()); 
    } 
    public int[] longParser(Long key) 
    { 
     System.out.println("Parsing long to crypto keys..."); 
     int i = 0; 
     int[] result; 
     String sInput = new String(key.toString()); 
     char[] keys = new char[sInput.length()]; 
     for(i = 0; i < sInput.length(); i++) 
     { 
      keys[i] = sInput.charAt(i); 
     } 
     i = 0; 
     result = new int[sInput.length()]; 
     for(i=0; i<keys.length; i++) 
     { 
      result[i] = (int) keys[i]; 
     } 
     return result; 
    } 
} 

The input I gave it that broke the program was
123089648734
爲重點,並
R EWW'U( AO)TP(MO \ QAU) 爲密文。它應該出來

我不想這樣做!'

我只是想知道,如果任何人都可以修改代碼,因此不會與這些問題的答案放棄。

+1

「我不知道代碼格式是否按照我的方式經過了這裏。「當您在問題的文本區域下鍵入時,您有預覽屏幕。你可能想用它來設置你的問題的格式。 – Nishant 2011-02-02 04:54:35

+0

我正在研究它。我現在編輯了幾次並修復了它。抱歉。 – 2011-02-02 04:56:29

回答

0

問題出在您的輸入處理,而不是您的算法。默認情況下,java.util.Scanner爲空白字符(包括輸入字符串的第二個字符所在的空格)分隔標記。所以你對in.next()的調用返回一個帶有單個字符('R')的字符串,然後處理它並返回單個字符的輸出。

一個快速的方法來解決它是用Scanner.nextLine(抓住你的輸入文本),而不是未來,這將讓所有的字符就行(包括空格):

System.out.print("Enter your Cipher Text message :"); 
in.nextLine(); 
plainTxt = new String(in.nextLine());