首页 > 解决方案 > 当我按下按钮时,JFrame 冻结

问题描述

我正在制作一个加密程序,由于某种原因,当我按下按钮时程序完全冻结了。我不确定出了什么问题,因为我以前做过很多简单的 GUI,但我从来没有遇到过这个问题。这是按钮的空白:

private void btnEncryptActionPerformed(java.awt.event.ActionEvent evt) {                                           
        String origMessage = txtDInput.getText();
        String encMessage = "";
        String revMessage = "";
        String extraStg1 = "";
        String extraStg2 = "";
        char tempChar;
        char tempExtraChar;
        int tempAscii;
        int tempExtraAscii;
        
        for (int i = origMessage.length() - 1; i >= 0; i = i--) //reverses message
        {
            revMessage = revMessage + origMessage.charAt(i);
        }
        
        for (int i = 0; i < revMessage.length(); i = i++)
        {
            tempChar = revMessage.charAt(i); //stores character in the tempChar variable
            tempAscii = (int)tempChar; //converts the character into an Ascii value
            tempAscii = tempAscii + 3; //adds 3 to Ascii value
            tempChar = (char)tempAscii; //converts Ascii value back into a character value
            encMessage = encMessage + tempChar; //adds the new character to the encrypted string and repeats for every character
        }
        
        for (int i = 0; i <= 7; i++)
        {
            tempExtraAscii = (int)Math.round(Math.random()*25+1+96); //generates a random integer between 97 and 122
            tempExtraChar = (char)tempExtraAscii; //convert the random integer into a character
            extraStg1 = extraStg1 + tempExtraChar; //add the extra character to tempExtraStg1
        }
        
        for (int i = 0; i <= 7; i++)
        {
            tempExtraAscii = (int)Math.round(Math.random()*25+1+96); //generates a random integer between 97 and 122
            tempExtraChar = (char)tempExtraAscii; //convert the random integer into a character
            extraStg2 = extraStg2 + tempExtraChar; //add the extra character to tempExtraStg2
        }
        
        encMessage = extraStg1 + encMessage + extraStg2;
        
        txtEncrypted.setText(encMessage);
    } 

我是这方面的初学者,所以如果答案尽可能简单,我将不胜感激。谢谢。

标签: java

解决方案


这就是问题:

for (int i = 0; i < revMessage.length(); i = i++)

i = i++是一个无操作 - 它递增i,但随后将其设置回原始值,因此您的循环将永远执行。只需将其更改为:

for (int i = 0; i < revMessage.length(); i++)

您实际上之前遇到了同样的问题:

for (int i = origMessage.length() - 1; i >= 0; i = i--)

应该

for (int i = origMessage.length() - 1; i >= 0; i--)

(作为旁注,这并不是真正有用的“加密”,无论如何你都不应该推出自己的加密,但我已经按照要求解决了这个问题。)


推荐阅读