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
as the key, and
R EWW'U(AO)TP(MO!\QAU) as the ciphertext. It should come out to

我不想那样做!`

我只想知道是否有人可以修复代码,这样它就不会放弃这些答案。

4

1 回答 1

0

问题在于您的输入处理,而不是您的算法。默认情况下,java.util.Scanner 在空白字符(包括作为输入字符串的第二个字符的空格)上分隔标记。因此,您对 in.next() 的调用将返回带有单个字符 ('R') 的字符串,然后对其进行处理并返回单个字符的输出。

解决它的一种快速方法是使用 Scanner.nextLine() 而不是 next 获取输入文本,这将获取行上的所有字符(包括空格):

System.out.print("Enter your Cipher Text message :");
in.nextLine();
plainTxt = new String(in.nextLine());
于 2011-02-02T06:22:06.933 回答