做caesar密码时JAVA索引问题

时间:2014-04-01 11:10:23

标签: java arrays string

代码目标:(使用netbeans)

我试图编写此代码以应用凯撒密码算法,其中可以按顺序使用多个密钥,例如:key = [1,2,3],text = test,其中它将使用密钥作为" 1"在" t"然后关键" 2"在" e"然后键#34; 3"在" s"然后回到关键" 1"在最后t。

输出:

run:
Enter the text : mohammad rahmat
Enter the number of keys you want to use : 3
Enter 3 number of keys : 1
2
3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at caesar.Caesar.main(Caesar.java:68)
nqkbopbfbsckncw
Java Result: 1
BUILD SUCCESSFUL (total time: 9 seconds)

代码:

package caesar;    

import java.util.Scanner;    

public class Caesar {

/**
 * @param args the command line arguments
 */
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
    // TODO code application logic here
    char table[] = {'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',' ','.'};
    String tmp;
    System.out.print("Enter the text : ");
    tmp = input.nextLine();
    char text[] = tmp.toCharArray();
    System.out.print("Enter the number of keys you want to use : ");
    int keyNo = input.nextInt();
    int key[] = new int[keyNo];
    System.out.printf("Enter %d number of keys : ",keyNo);
    for (int i = 0; i < keyNo; ++i){
        key[i] = input.nextInt();
    }

    char entext[] = new char[text.length];
    int k = 0;
    int a = 0;
    int count = 0;
    while (k < text.length){
        int j = 0;
        while (text[a] != table[j])
            j++;
        if (key[count]+j >= table.length){
            entext[a] = table[(j+key[count])%table.length];
        }

        else entext[a] = table[j+key[count]];

        a++;
        count++;
        if (count == keyNo)
            count = 0;
        k++;


    }
    String answer = new String(entext);
    System.out.printf("ENCRYPTION : %s \n\n",answer);


    char detext[] = new char[text.length];
    k = 0;
    a = 0;
    count = 0;
    while (k < text.length){
        int j = 0;
        while (text[a] != table[j])
            j++;
        if (key[count]-j < 0){
            detext[a] = table[table.length+(key[count]-j)];
        }

        else detext[a] = table[j-key[count]];

        a++;
        count++;
        if (count == keyNo)
            count = 0;
        k++;


    }
    String answer2 = new String(detext);
    System.out.printf("DECRYPTION : %s\n\n",answer2);
}
}

2 个答案:

答案 0 :(得分:0)

您应该使用调试器来分析您的代码。

detext[a] = table[table.length+(key[count]-j)];

您正在递增j并将其从count减去零。在找到查找数组索引之前增加count

答案 1 :(得分:0)

我终于找到了它,在将其转换回原始文本时,我不得不接受转换后的文本,换句话说:

替换

while (k < text.length){
    int j = 0;
    while (text[a] != table[j])

while (k < entext.length){
        int j = 0;
        while (entext[a] != table[j])