程序在执行简单循环时冻结

时间:2011-08-10 17:16:17

标签: java

此代码:

class X {

    private char encryptChar(String input, int pos) {
        //do not worry about "lengtness" it's just for debugging purposes
        int length = keyString.length();//key string is "CD10"
        int pos_ = pos % keyString.length();
        char l_ = input.charAt(pos_);
        char r_ = keyString.charAt(pos_);
        int result = l_ ^ r_;
        char rr = (char) result;
        return (char) result;
    }

    public String encryptString(String message) {

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < message.length();++i) {
            result.append(encryptChar(message,i));//after one iteration this freezes! why?
        }
        return result.toString();
    }
}

请参阅上面两行的评论。 O,我正在使用NetBeans 7.0.1

1 个答案:

答案 0 :(得分:2)

考虑使用更有意义的变量名称。您发布的代码中此行有一个错误:char l_ = input.charAt(pos_); 而不是“pos_”,参数应为“pos”。


    private char encryptChar(String input, int inputPosition)
    {
        char encryptCharacter;
        int encryptPosition = inputPosition % KEY_STRING.length();
        char inputCharacter;
        char returnValue;

        encryptCharacter = KEY_STRING.charAt(encryptPosition);
        inputCharacter = input.charAt(inputPosition);
        returnValue = (char) (encryptCharacter ^ inputCharacter);

        return returnValue;
    }

    private String encryptString(String message)
    {
        StringBuilder result = new StringBuilder();

        for (int index = 0; index < message.length(); ++index)
        {
            result.append(encryptChar(message, index));
        }

        return result.toString();
    }