2011-02-02 101 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());