使用多键凯撒密码时可能出现无限循环错误

时间:2017-05-01 01:27:33

标签: java queue encode caesar-cipher

这个程序编译,但在我输入单个键值后,程序不会输出任何内容(没有错误),并且有效地结束。它应该使用键值列表将每个字符移动不同的量。例如,如果键值为3 1 7 -4 2 5,则第一个字符移位3,第二个字符移1,依此类推(在ASCII字符图表上)。将第六个字符移动5后,我再次开始使用该键。我已经为Queue接口实现了一个Node和Queue类。

这是我的班级:

public class Cipher
{
    public static void main(String[] args)
    {
        Scanner kb = new Scanner(System.in);
        Queue keys = new Queue();
        int n;
    String answer, message, encrypted = "", decrypted = "";

        do
        {
            System.out.println("Enter the number of key values:");
            n = kb.nextInt();

            System.out.println("Enter the individual key values:");

            while (kb.hasNextInt())
                keys.enqueue((Integer)kb.nextInt());

            int initial = Integer.parseInt((String)keys.peek());

            System.out.println("Enter a string to be encoded:");
            message = kb.nextLine();

            for(int j=0; j < message.length(); j++)
            {
                keys.enqueue(keys.peek());
                encrypted += encode(message.charAt(j), Integer.parseInt((String)keys.dequeue()));
            }

            System.out.println("The encoded message is: " + encrypted);

            while (Integer.parseInt((String)keys.peek()) != initial)
            {
                keys.enqueue(keys.peek());
                keys.dequeue();
            }

            for(int k = 0; k < message.length(); k++)
            {
                keys.enqueue(keys.peek());
                decrypted += decode(message.charAt(k), Integer.parseInt((String)keys.dequeue()));
            }

            System.out.println("The decoded message is:" + decrypted);
            System.out.println("Would you like to run the program again? (yes/no)");
            answer = kb.nextLine();
        }
        while (answer.equalsIgnoreCase("yes"));
    }

    public static String decode(char enc, int offset) {
        return encode(enc, 26-offset);
    }

    public static String encode(char enc, int offset) {
        offset = offset % 26 + 26;
        StringBuilder encoded = new StringBuilder();
        if (Character.isUpperCase(enc)) {
                encoded.append((char) ('A' + (enc - 'A' + offset) % 26 ));
                }
         else {
                encoded.append((char) ('a' + (enc - 'a' + offset) % 26 ));
                }
        return encoded.toString();
    }
}

我认为错误与while循环有关:<​​/ p>

System.out.println("Enter the individual key values:");

            while (kb.hasNextInt())
                keys.enqueue((Integer)kb.nextInt());

            int initial = Integer.parseInt((String)keys.peek());

0 个答案:

没有答案